【问题标题】:Fastest method to filter XmlDocument xml in C#在 C# 中过滤 XmlDocument xml 的最快方法
【发布时间】:2021-09-18 00:08:32
【问题描述】:

我有一个包含以下 xml 的 XmlDocument 对象:

<xml>
    <People>
        <Person>
            <FirstName>John</FirstName>
            <Surname>Smith</Surname>
            <Type>A</Type>
        </Person>
        <Person>
            <FirstName>Bill</FirstName>
            <Surname>Smith</Surname>
            <Type>B</Type>
        </Person>
        <Person>
            <FirstName>Chad</FirstName>
            <Surname>Smith</Surname>
            <Type>B</Type>
        </Person>
        <Person>
            <FirstName>Tina</FirstName>
            <Surname>Johnson</Surname>
            <Type>B</Type>
        </Person>
    </People>
</xml>

我想将 Surname 节点设置为 Smith 且 Type 设置为 B 的 xml 过滤到另一个 XMLDocument 对象中,如下所示:

<xml>
    <People>
        <Person>
            <FirstName>Bill</FirstName>
            <Surname>Smith</Surname>
            <Type>B</Type>
        </Person>
        <Person>
            <FirstName>Chad</FirstName>
            <Surname>Smith</Surname>
            <Type>B</Type>
        </Person>
    </People>
</xml>

用上面提到的 C# 标准过滤我的 xml 的最简单/最快的方法是什么?有没有办法在 Linq 中做到这一点?我尝试使用 SelectNodes 和 XPath,但不确定如何正确编写 XPath 表达式。

谢谢!

编辑:想通了:

descendant::Person[Surname='Smith' and Type='B']

【问题讨论】:

    标签: c# xml linq xpath xmldocument


    【解决方案1】:

    尝试以下:

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Xml;
    using System.Xml.Linq;
    namespace ConsoleApplication193
    {
        class Program
        {
            const string FILENAME = @"c:\temp\test.xml";
            static void Main(string[] args)
            {
                XDocument doc = XDocument.Load(FILENAME);
                XElement people = doc.Descendants("People").FirstOrDefault();
    
                List<XElement> smith = people.Elements("Person").Where(x => (string)x.Element("Surname") == "Smith").ToList();
    
                people.ReplaceAll(smith);
    
            }
        }
    }
    

    【讨论】:

    • 感谢您的建议!你错过了我也检查类型的地方。我还想出了如何使用似乎可行的 xpath 表达式! descendant::Person[Surname='Smith' and Type='B']
    猜你喜欢
    • 2016-12-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-03
    • 2011-03-04
    • 2010-12-15
    • 1970-01-01
    • 2012-06-28
    相关资源
    最近更新 更多