如何为XML创建XPath?

Pan*_*hra 2 c# xml xpath linq-to-xml xml-parsing

我有一个Xml文件,我想在其中基于XPath进行过滤.我尝试了很多例子他们都没有帮助毫无疑问我犯了一些错误.我是XPath的新手请帮我找到解决方案.

<PeopleBatch Counter="3">
<Citriz ID="1d9a88fe-f9cc-4add-b6d1-01e41c561bfb" mVersion="1.0.0" mSequence="1" pVersion="0.0.1" xmlns="http://Citriz/Schemas">
    <People Action="U" Status="CD" PeopleID="1" PeopleShortName="Billy" PeopleLongName="Billy Smith" PeopleTypeCode="Commercial" CountryCode="USA" PeopleStatus="Current">
            <PeopleRole Action="U" Status="CD" ID="1" CustomerRoleShortName="Billy" CustomerRoleLongName="Billy Smith" TypeCode="OUTS">
                    <SendRole RoleType="N" ActiveRole="Y"/>
            </PeopleRole>
    </People>
</Citriz>
<Citriz ID="1d9a88fe-f9cc-4add-b6d1-01e41c561bfc" mVersion="1.0.0" mSequence="2" pVersion="0.0.1" xmlns="http://Citriz/Schemas">
    <People Action="U" Status="CD" PeopleID="2" PeopleShortName="Carl" PeopleLongName="Carl Thomas" PeopleTypeCode="Commercial" CountryCode="USA" PeopleStatus="Current">
            <PeopleRole Action="U" Status="CD" ID="2" CustomerRoleShortName="Carl" CustomerRoleLongName="Carl Thomas" TypeCode="INSS">
                    <SendRole RoleType="N" ActiveRole="Y"/>
            </PeopleRole>
    </People>
</Citriz>   
<Citriz ID="1d9a88fe-f9cc-4add-b6d1-01e41c561bfd" mVersion="1.0.0" mSequence="3" pVersion="0.0.1" xmlns="http://Citriz/Schemas">
    <People Action="U" Status="CD" PeopleID="3" PeopleShortName="Ryan" PeopleLongName="Ryan Black" PeopleTypeCode="Commercial" CountryCode="USA" PeopleStatus="Current">
            <PeopleRole Action="U" Status="CD" ID="3" CustomerRoleShortName="Ryan" CustomerRoleLongName="Ryan Black" TypeCode="INSS">
                    <SendRole RoleType="N" ActiveRole="Y"/>
            </PeopleRole>
    </People>
</Citriz>   
Run Code Online (Sandbox Code Playgroud)

我需要所有那些"Citriz"节点,其子节点属性包含TypeCode ="INSS"这个值.或者建议我,如果有任何其他好方法.

Jon*_*eet 6

鉴于您正在使用LINQ to XML,我不会使用XPath开始.我用的是:

XNamespace ns = "http://Citriz/Schemas";
var nodes = doc.Descendants(ns + "Citriz")
               .Where(x => x.Descendants()
                            .Any(y => (string) x.Attribute("TypeCode") == "INSS"));
Run Code Online (Sandbox Code Playgroud)

或者,如果它总是将成为PeopleRole内侧元件PeopleCitriz(在每个级别只是一个单一的元素):

XNamespace ns = "http://Citriz/Schemas";
var nodes = doc.Descendants(ns + "Citriz")
               .Where(x => (string) x.Element(ns + "People")
                                     .Element(ns + "PeopleRole")
                                     .Attribute("TypeCode") == "INSS"));
Run Code Online (Sandbox Code Playgroud)

我确信这可以在XPath中合理地完成,但我个人认为LINQ to XML更简单,在分离数据部分(元素名称,期望值等)与"代码"部分分开("我正在寻找对于后代"或"我正在寻找一个属性值").