如何为XML创建XPath

本文关键字:创建 XPath XML | 更新日期: 2023-09-27 18:11:48

我有一个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>   

我需要所有那些"Citriz"节点子节点属性包含TypeCode="INSS"这个值。

如何为XML创建XPath

考虑到您正在使用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"));

或者如果是总是PeopleRole元素在People中,Citriz中(每层只有一个元素):

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

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

我想你对Xml命名空间有问题

XNamespace ns = "http://Citriz/Schemas";
var peopleRole = XDocument.Parse(xml)
                    .Descendants(ns + "PeopleRole")
                    .Where(p => p.Attribute("TypeCode").Value == "INSS")
                    .ToList();

可以认为XPath相当于在文件系统中的目录树中导航。在xpath查询中添加额外的"目录"可以让您更深入地了解DOM树。

//PeopleRole[@TypeCode="inss"]/../..

将找到类型为PeopleRole的所有节点,其TypeCode属性等于'inss',然后向上移动到树中的各个级别,返回包含匹配的PeopleRole的<Citriz>节点