'Getting multiple values based on a unknown condition
I have following scenarion. I have a given XML structure and in there, there is a XML block defined as like this:
<CHARACTERISTICS>
<CHARACTERISTIC id="BLOCK1">
<CODE>H318</CODE>
<FILENAME/>
<TEXT>VALUE1</TEXT>
</CHARACTERISTIC>
<CHARACTERISTIC id="BLOCK1">
<CODE>H318</CODE>
<FILENAME/>
<TEXT>VALUE2</TEXT>
</CHARACTERISTIC>
<CHARACTERISTIC id="BLOCK1">
<CODE>PZ123</CODE>
<FILENAME/>
<TEXT>VALUE3</TEXT>
</CHARACTERISTIC>
</CHARACTERISTICS>
Is there any way to have an outcome like this:
- Value Entry1: H318
- Value Entry2: VALUE1 VALUE2
?
So what I try to achieve is, giving on the code to get every TEXT entry based on an unknown CODE. Is that possible with XPATH?
Solution 1:[1]
A, very simple, example:
using System.Xml.Linq;
XDocument doc = XDocument.Load("CHARACTERISTICS.xml");
foreach (XElement item in doc.Descendants("CHARACTERISTIC"))
{
var Code = item.Elements("CODE").FirstOrDefault().Value;
var Text = item.Elements("TEXT").FirstOrDefault().Value;
Console.WriteLine($"{Code},{Text}");
}
This will output (with given example input):
H318,VALUE1
H318,VALUE2
PZ123,VALUE3
or:
using System.Xml;
XmlDocument xml = new XmlDocument();
xml.Load("CHARACTERISTICS.xml");
foreach (XmlNode item in xml.SelectNodes("//CODE"))
{
XmlNode text = item.SelectSingleNode("../TEXT");
Console.WriteLine($"{item.InnerText},{text.InnerText}");
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
