识别 XDocument 中的 HTML 个节点以替换和转换为 Json
Identify HTML nodes in XDocument for replacement and translation to Json
我有 XML 个包含 HTML 个标签。使用 XDocument
我可以找到节点并替换内容以删除 HTML 标签。有没有办法用 HTML 标签识别节点,以便可以在所有节点上进行相同的替换?这是一些示例 XML.
<?xml version="1.0" encoding="utf-8"?>
<myFields>
<Request_Description>
<html>
<div>test</div>
</html>
</Request_Description>
<Alternatives>
<html>
<div>n/a</div>
</html>
</Alternatives>
<Outcome>
<html>
<div>n/a</div>
</html>
</Outcome>
</myFields>
这就是我想出如何按名称替换单个节点的 HTML 的方法。
XElement req_desc = newxdoc.Root.Element("Request_Description");
if (req_desc != null)
{
XElement replacenode = new XElement(req_desc.Name, req_desc.Value);
req_desc.Parent.Add(replacenode);
req_desc.Remove();
}
我可以为 "Alternatives" 和 "Outcome" 做同样的事情。但是这些节点中的每一个都应该可以通过它们的下一个子节点具有本地名称 "html" 的事实来识别。我怎样才能找到第一个子元素的本地名称为 "html" 的元素,然后执行我上面执行的替换步骤以删除该 HTML 代码?
您可以使用 XDocument
的 Descendants
方法查找文档中第一个子元素的本地名称为 "html"
的所有 XML 元素,如下所示:
var query = from e in newxdoc.Descendants()
//find those elements whose first child has the local name of "html"
let child = e.Elements().FirstOrDefault()
where child != null && child.Name.LocalName == "html"
select e;
foreach (var element in query.ToList())
{
// Remove html and replace with plain text.
var replacenode = new XElement(element.Name, element.Value);
element.ReplaceWith(replacenode);
}
示例 fiddle here.
我有 XML 个包含 HTML 个标签。使用 XDocument
我可以找到节点并替换内容以删除 HTML 标签。有没有办法用 HTML 标签识别节点,以便可以在所有节点上进行相同的替换?这是一些示例 XML.
<?xml version="1.0" encoding="utf-8"?>
<myFields>
<Request_Description>
<html>
<div>test</div>
</html>
</Request_Description>
<Alternatives>
<html>
<div>n/a</div>
</html>
</Alternatives>
<Outcome>
<html>
<div>n/a</div>
</html>
</Outcome>
</myFields>
这就是我想出如何按名称替换单个节点的 HTML 的方法。
XElement req_desc = newxdoc.Root.Element("Request_Description");
if (req_desc != null)
{
XElement replacenode = new XElement(req_desc.Name, req_desc.Value);
req_desc.Parent.Add(replacenode);
req_desc.Remove();
}
我可以为 "Alternatives" 和 "Outcome" 做同样的事情。但是这些节点中的每一个都应该可以通过它们的下一个子节点具有本地名称 "html" 的事实来识别。我怎样才能找到第一个子元素的本地名称为 "html" 的元素,然后执行我上面执行的替换步骤以删除该 HTML 代码?
您可以使用 XDocument
的 Descendants
方法查找文档中第一个子元素的本地名称为 "html"
的所有 XML 元素,如下所示:
var query = from e in newxdoc.Descendants()
//find those elements whose first child has the local name of "html"
let child = e.Elements().FirstOrDefault()
where child != null && child.Name.LocalName == "html"
select e;
foreach (var element in query.ToList())
{
// Remove html and replace with plain text.
var replacenode = new XElement(element.Name, element.Value);
element.ReplaceWith(replacenode);
}
示例 fiddle here.