How to use value of one node as a node itself
<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])
精彩评论