Skip to main content
 首页 » 编程设计

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

2024年05月22日34fff_TT

我有使用 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 那样简单:)