使用XPathSelectElements对不区分大小写的元素进行选择

时间:2017-01-17 06:05:50

标签: c# xml xpath

我需要通过忽略大小写来从xml以下使用XPath获取<aw:Child1>个元素。

<aw:Root xmlns:aw='http://www.test-works.com'>
    <aw:Child uid='Test1'>child one data 1</aw:Child>
    <aw:Child uid='Test2'>child one data 2</aw:Child>
    <aw:Child uid='Test3'>child one data 3</aw:Child>
</aw:Root>

这是我的代码,但它永远不会返回任何元素:

      string markup = @"
<aw:Root xmlns:aw='http://www.test-works.com'>
    <aw:Child uid='Test1'>child one data 1</aw:Child>
    <aw:Child uid='Test2'>child one data 2</aw:Child>
    <aw:Child uid='Test3'>child one data 3</aw:Child>
</aw:Root>";
            var reader = XmlReader.Create(new StringReader(markup));
            var root = XElement.Load(reader);
            var nameTable = reader.NameTable;
            var namespaceManager = new XmlNamespaceManager(nameTable);
            namespaceManager.AddNamespace("aw", "http://www.test-works.com");

            var inputQuery = "./aw:Child[@uid='test1']"; //Auto generated

            var elements = root.XPathSelectElements(inputQuery, namespaceManager);
            foreach (var el in elements)
                Console.WriteLine(el);

当我更改正确的案例

的路径时,我得到了结果
var inputQuery = "./aw:Child[@uid='Test1']";

但要匹配的元素是动态生成的,并且始终是小写的。在匹配元素时有没有办法忽略大小写?

1 个答案:

答案 0 :(得分:0)

您可以使用XPath 1.0 translate()函数将所有大写字符替换为小写。 在你的情况下,它将是:

var inputQuery = "./aw:Child[translate(@uid, 'ABCDEFGHIJKLMNOPQRSTUVWXYZ', 'abcdefghijklmnopqrstuvwxyz')='test1']";