c# - 将 XmlNodeList 的内容转换为新的 XmlDocument,无需循环

标签 c# xml xpath xmldocument xmlnodelist

我有使用 XPath 过滤的 Xml(与此类似的查询):

    XmlNodeList allItems = 
xDoc.SelectNodes("//Person[not(PersonID = following::Person/PersonID)]");

这会过滤我原始 Persons Xml 中的所有重复项。我想从上面生成的 XmlNodeList 创建一个新的 XmlDocument 实例。目前,我能想到的唯一方法是循环遍历 XmlNode 列表并构建一个 Xml 字符串(如此):

        XmlNodeList allItems = xDoc.SelectNodes("//Person[not(PersonID = following::Person/PersonID)]");
        StringBuilder xml = new StringBuilder("<Persons>");

        foreach (XmlNode node in allItems)
            xml.Append(node.OuterXml);

        xml.Append("</Persons>");

        XmlDocument newXDoc = new XmlDocument();
        newXDoc.LoadXml(xml.ToString());

必须有一种更有效的方法来做到这一点吗?

最佳答案

如果您愿意将其转换为 LINQ to XML,那么这非常简单:

XDocument original = ...; // However you load the original document
// Separated out for clarity - could be inlined, of course
string xpath = "//Person[not(PersonID = following::Person/PersonID)]"

XDocument people = new XDocument(
    new XElement("Persons",
        original.XPathSelectElements(xpath)
    )
);

您绝对不需要将每个节点转换为字符串并返回。您也不需要使用 XmlDocument,但它不会像使用 LINQ to XML 那样简单:)

关于c# - 将 XmlNodeList 的内容转换为新的 XmlDocument,无需循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30975591/

相关文章:

c# - 按名称、标签或图层查找不活动的游戏对象

c# - 在 C# 中,如何在不逐行搜索的情况下在大型文本文件中搜索字符串?

c# - Xamarin.Forms 中带有图像的短信

php - 我是使用 fopen 还是 curl 加载给定 PHP 中的 URL 的 XML 文件

c# - 为什么我的 xml 文档被视为一个元素?

c# - 更改要导入到 Access 数据库的 Xml 的结构

RegEx/XPath 以匹配 XML 中的某些 Adob​​e LiveCycle Designer 字段

c# - Windows 版本在设计中显示出真正的值(value),但在我运行程序时显示出不同的值(value)

html - Xpath 得到一个如果 href 包含字符串的一部分

java - 使用 Xpath 提取属性