简体   繁体   中英

How to get the next text of an XML node, with C#?

I have the following XML. Given the classname, I need to get its corresponding colorcode. How can I accomplish this in C# ? Otherwise said, I have to get to a specific node, given its previous node's text. Thank you very much

<?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>...

将xml加载到XmlDocument中,然后执行:

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

With your xml loaded into a 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, the use of following-sibling means that I assume the same element ordering as in the original example.

My Linq version seems slightly 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;
}

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

XmlDocument.SelectSingleNode is your solution. There is a pretty good example provided as an example.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM