开发者

How to use value of one node as a node itself

开发者 https://www.devze.com 2023-02-17 22:08 出处:网络
<root> <node1>value1</node1> <node2>something</node2> <something>somevalue</something>
<root>
     <node1>value1</node1>
     <node2>something</node2>
     <something>somevalue</something>
<root>

How to form a XPath which would 开发者_如何学运维fetch the value 'somevalue' in the above XML example? The tag something is itself a value of <node2>

In future <node2> may have some different value say anything Which would ultimately result in having anything as a tag as shown below

<node2>anything</node2>
<anything>somevalue</anything>

something/anything tags would be there depending on value of <node2>

How to form XPath for above case?


This code contains a couple of ways to do it. The latter uses a single xpath statement:

public void DoXML()
{
    System.Xml.XmlDocument doc = new System.Xml.XmlDocument();
    doc.LoadXml("<root><node1>value1</node1><node2>something</node2><something>somevalue</something></root>");

    //Option 1 - two statements
    string nodeName = doc.DocumentElement.SelectSingleNode("node2").InnerText;
    string value1 = doc.DocumentElement.SelectSingleNode(nodeName).InnerText;
    Console.WriteLine(value1);

    //Option 2 - single statement
    string value2 = doc.DocumentElement.SelectSingleNode("node()[name() = ../node2]").InnerText;
    Console.WriteLine(value2);

}


The following xpath should work:

/root/*[name()=/root/node2]

It returns a node with the same name as the value of /root/node2.


From comments of the OP it becomes clear that the XML document is more complex:

Use:

  /*/*[name() = /*/node2]/tag1

Or use:

  string(/*/*[name() = /*/node2]/tag1)

Or use:

  /*/*[name() = /*/node2]/text()[1]

Or use:

  string(/*/*[name() = /*/node2]/text()[1])
0

精彩评论

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