How to get the following XML node text, from C #?

I have the following XML. Given the class name, I need to get the corresponding color code. How can I do this in C #? Otherwise, I have to go to a specific node, given its previous text node. Many thanks

<?xml version="1.0" encoding="ISO-8859-1" standalone="yes"?>
<?xml-stylesheet type='text/xsl' href='template.xslt'?>
<skin name="GHV--bordeaux">
  <color>
    <classname>.depth1</classname>
    <colorcode>#413686</colorcode>
  </color>
  <color>
    <classname>.depth2</classname>
    <colorcode>#8176c6</colorcode>
  </color>...
+3
source share
4 answers

Load xml into XmlDocument, and then do:

document.SelectSingleNode("/skin/color[classname='.depth1']/colorcode").InnerText
+8
source

With your xml loaded into the document.

var color = document.CreateNavigator().Evaluate("string(/skin/color/classname[. = '.depth']/following-sibling::colorcode[1])") as string;

This will return one of your color codes or an empty string.
As @Dolphin notes, using the following sibling means that I accept the same order of elements as in the original example.

My version of Linq looks a bit more verbose:

var classname = ".depth1";
var colorcode = "";

XElement doc = XElement.Parse(xml);

var code = from color in doc.Descendants("color")
    where classname == (string) color.Element("classname")
    select color.Element("colorcode");

if (code.Count() != 0) {
    colorcode = code.First().Value;
}
+5

Xpath will be useful ... // skin / color [classname = '.depth1'] / colorcode will return # 413686. Load xml into XmlDocument. Then use the .SelectSingleNode method and use Xpath, changing the class name as needed.

0
source

XmlDocument.SelectSingleNode is your solution. An example is a pretty good example.

0
source

Source: https://habr.com/ru/post/1730394/


All Articles