can someone help me with this xml? How i can get the value hodnota
from for eg. attribute named PC0.1
<items>
<item kod_zbozi="1010113414">
<Parametr kod_parametru="PC0.1" hodnota="AutoCont Allegro" />
<Parametr kod_parametru="PC4.2" hodnota="Windows 10 Pro" />
</item>
<item kod_zbozi="1011124131">
<Parametr kod_parametru="PC0.1" hodnota="AutoCont OfficePro" />
<Parametr kod_parametru="PC4.2" hodnota="Windows 10 Pro" />
</item>
<item kod_zbozi="1011124135">
<Parametr kod_parametru="PC0.1" hodnota="AutoCont OfficePro" />
<Parametr kod_parametru="PC4.2" hodnota="Windows 10 Pro" />
</item>
<item kod_zbozi="1011124139">
<Parametr kod_parametru="PC0.1" hodnota="AutoCont OfficePro" />
<Parametr kod_parametru="PC4.2" hodnota="Windows 11 Pro" />
</item>
<item kod_zbozi="1011124145">
<Parametr kod_parametru="PC0.1" hodnota="AutoCont OfficePro" />
<Parametr kod_parametru="PC4.2" hodnota="Windows 10 Pro" />
</item>
<item kod_zbozi="1011340128">
<Parametr kod_parametru="PC0.1" hodnota="AutoCont OfficePro" />
<Parametr kod_parametru="PC4.2" hodnota="Windows 10 Pro" />
</item>
</items>
thank you
CodePudding user response:
Assume this xml string is xmlData
, you can get the output
like this
using System.Xml;
// ..
var output = new List<string>();
var xmlDoc = new XmlDocument();
xmlDoc.LoadXml(xmlData);
var nodes = xmlDoc.SelectNodes("items/item/Parametr");
if (nodes != null)
foreach (XmlNode node in nodes)
{
if (node.Attributes != null
&& node.Attributes["kod_parametru"]?.InnerText == "PC0.1"
&& node.Attributes["hodnota"] != null)
result.Add(node.Attributes["hodnota"].InnerText);
}
// output is ready (count = 6)
CodePudding user response:
You can get the output
using pattern matching (i.e. Regex).. Let's say this xml string is xmlData
var output = xmlData
.ExtractEveryStringSurrounded("kod_parametru=\"PC0.1\" hodnota=\"", "\" />");
// output is List<string>, count = 6
Where ExtractEveryStringSurrounded
is an extension function
public static class StringExtensions
{
public static List<string> ExtractEveryStringSurrounded(this string body, string start, string end)
{
var results = new List<string>();
if (string.IsNullOrEmpty(body)) return results;
var pattern = $"{Regex.Escape(start)}(. ?){Regex.Escape(end)}";
var r = new Regex(pattern, RegexOptions.IgnoreCase | RegexOptions.Singleline);
foreach (Match m in r.Matches(body))
results.Add(m.Groups[1].Value);
return results;
}
// other extensions
}