使用其值检索XML元素的XPath

时间:2010-03-24 06:43:41

标签: xml xml-serialization

我的XmlFile看起来像这样:

<?xml version="1.0"?> <document-inquiry> <publication-reference data-format="docdb" xmlns="http://www.epo.org/exchange"> <document-id> <country>EP</country> <doc-number>2160088</doc-number> <kind>A1</kind> </document-id> </publication-reference>
</document-inquiry>

对于上面的xml,我需要获取特定元素的xpath,例如“country element”,如

我的输出:“/ document-inquiry / publication-reference / document-id / country”

我的输入:使用其值“EP”

这是我试过的代码

doc.SelectSingleNode("/document-inquiry/publication-reference/document-id[text()='EP']");

我收到上述代码的null。

我必须使用c#代码。任何人都可以帮我这个

1 个答案:

答案 0 :(得分:1)

using System;
using System.Linq;
using System.Xml;
using System.Xml.Linq;
using System.Xml.XPath;

class Program
{
    static void Main()
    {
        var doc = XDocument.Load("D:\\xml\\neo.xml");
        var ns = new XmlNamespaceManager(new NameTable());
        ns.AddNamespace("ns", "http://www.epo.org/exchange");
        var elem = XDocument.Load("D:\\xml\\neo.xml")
            .XPathSelectElement("//ns:document-id[ns:doc-number='1000']", ns);
        if (elem != null)
        {
            Console.WriteLine(elem.ToString());
            Console.ReadLine();
        }
    }
}

这对我来说很有效。

相关问题