gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 06:11:30 24 4
gpt4 key购买 nike

我有使用 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com