开发者

How do I get XML path by its value?

I need to get the xml path opf the xml file by providing the value of an xml child element as the input.

For开发者_运维技巧 example:

XML file:

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

For the above XML file. I need to get the XML path by using the value "1000". If my input is value of the element "1000" Output i need is :

 <document-id>
        <country>EP</country>
        <doc-number>1000</doc-number>
        <kind>A1</kind>
  </document-id>

I need to achieve this using c# code. Can anyone please help me out on this...


You could use XPathSelectElement extension method:

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

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

You could use XPathSelectElements if you want to select multiple nodes that correspond to this criteria.


You can select the element that you want with a linq query.

var number = "1000";
var xml = XDocument.Parse( xml_string );
XNamespace ns = "http://www.epo.org/exchange";

var result = (from data in xml.Descendants(ns + "document-id")
           where data.Element(ns + "doc-number").Value == number
           select data).FirstOrDefault();

.FirstOrDefault() returns the first matching element or null. You could instead use .List() to get a list containing all matching elements.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜