开发者

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 accom开发者_开发问答plish 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>...


Load your xml into an XmlDocument and then do:

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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜