在不循环的情况下将 XmlNodeList 的内容转换为新的 XmlDocument

Convert contents of an XmlNodeList to a new XmlDocument without looping

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

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

这会过滤掉我原来的人物 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 那样简单 :)

有了XmlDocument你就可以使用

XmlDocument doc2 = new XmlDocument();
doc2.AppendChild(doc2.CreateElement("Persons"));
foreach (XmlElement person in allItems)
{
  doc2.DocumentElement.AppendChild(doc2.ImportNode(person, true));
}