Hasan Othman
Hasan Othman

Reputation: 78

How to Get XML Element by It's 'Value' using XML C# SDK

I have this snippt of XML

<unit class="xxx.xxx.xxx" id="382">
      <customId>000</customId>
      <description>kg</description>
      <key>22452</key>
      <Description>Kilogramm</Description>
 </unit>

how to get the node 'unit' or parnet of the key element using the value of an element. For instance

i have the value of key element above [22452] and it's Uniqe inside the xml-File.

what i am trying to do getting value of customid [000] of that specific tag.

what i did:

var doc = new XmlDocument();
doc.Load(stream); // stream from xml-file
var key = doc.SelectSingleNode(//key/[text()='" + 22452+ "']");  // that i am not sure about it.
var customId = key.InnerText("customId");

Upvotes: 0

Views: 158

Answers (2)

Amine.Benhebba
Amine.Benhebba

Reputation: 11

For this you can use Linq to Xml queries.

XElement units = XElement.Load("./Test.xml");

XElement unit = (from item in units.Descendants("unit")
                 where item.Element("key").Value == "22455"
                 select item).FirstOrDefault();

string customId = unit.Element("customId").Value;

supposing your xml file look like :

<?xml version="1.0" encoding="utf-8"?>
<units>
  <unit class="xxx.xxx.xxx" id="385">
    <customId>003</customId>
    <description>kg</description>
    <key>22455</key>
    <Description>Kilogramm</Description>
  </unit>
  <unit class="xxx.xxx.xxx" id="386">
    <customId>004</customId>
    <description>kg</description>
    <key>22456</key>
    <Description>Kilogramm</Description>
  </unit>
</units>

for more reading check Microsoft Linq to Xml Docs

Upvotes: 1

Richard
Richard

Reputation: 109035

For this kind of query you could either find the node and than navigate to the parent.

Or use XPath:

var unitElemnt = doc.SelectSingleNode("//unit[key = '22452']");

(Assuming I've remembered the XPath to match an element's text content correctly.)

This gets a reference to the <unit> element, by using a relative path to the <key> element in the predicate of the XPath expression.

Generally better to avoid // in XPath for performance, but would need full document structure to do that.

Upvotes: 3

Related Questions