表达式即使存在命名空间也能工作?

时间:2013-08-14 03:59:55

标签: c# .net xml xpath

我希望能够针对以下XML评估普通 XPath表达式,该XML具有我不关心的令人讨厌的xmlns属性:

<?xml version="1.0" encoding="UTF-8"?>
<?xml-stylesheet type="text/xsl" href="AuthorIT.xslt"?>
<AuthorIT version="6.0.8" xmlns="http://www.authorit.com/xml/authorit" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.authorit.com/xml/authorit AuthorIT.xsd">
    <Objects>
        <Book>
            <Object>
                <CreatedBy>Me</CreatedBy>
                <CreatedDate>2012-11-20T12:35:33</CreatedDate>
                <Description>String I want to get</Description>
                <FolderID>12345</FolderID>
                <GUID>abcdefg1234567abcdefg1234567abcd</GUID>
                <ID>99999</ID>
            </Object>
        </Book>
    </Objects>
</AuthorIT>

在XMLSpy(或this free web tool)中,“我想要获取的字符串”的表达式如下:

/AuthorIT/Objects/Book/Object/Description

这就是我在c#中指定命名空间的方法:

XPathDocument document = new XPathDocument("/path/to/my/file");
XPathNavigator navigator = document.CreateNavigator();
XmlNamespaceManager manager = new XmlNamespaceManager(navigator.NameTable);
manager.AddNamespace("abc", "http://www.authorit.com/xml/authorit");

一旦我指定了命名空间,这就是我必须修改完美的XPath表达式以获得相同的结果:

/abc:AuthorIT/abc:Objects/abc:Book/abc:Object/abc:Description

太可怕了,不是吗?!有没有办法评估XPath表达式绕过并完全忽略AuthorIT根元素上这个非常讨厌的“xmlns”属性的存在?如果我完全剥离根元素以使它只是它本身,我不需要指定命名空间,我可以使用普通表达式。有没有办法告诉.NET工作,好像首先不存在“xmlns”垃圾一样?

1 个答案:

答案 0 :(得分:1)

是的,有一种方法可以使用/local-name()='AuthorIT'/local-name()='Objects'/local-name()='Book'/local-name()='Object'/local-name()='Description'

相关问题