2010-01-28 61 views
3

我有以下XML。鉴于类名,我需要获取其相应的颜色代码。我怎样才能在C#中完成这项工作? 否则说,我必须得到一个特定的节点,给定它的前一个节点的文本。 非常感谢您如何使用C#获取XML节点的下一个文本?

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

回答

8

加载你的XML到XmlDocument,然后做:

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

Xpath的将是有益的... //皮肤/颜色[类名=” .depth1' ] /颜色代码将返回#413686。将你的xml加载到一个XmlDocument中。然后使用.SelectSingleNode方法并使用Xpath,根据需要更改类名。

5

将您的xml加载到文档中。

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

这将返回一个颜色代码或一个空字符串。
正如@Dolphin所指出的那样,使用跟随 - 同胞意味着我假设原始示例中的元素排序相同。

我的LINQ的版本似乎稍微详细:

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; 
} 
+0

如果类名/的ColorCode的顺序并不总是相同的例子这将失败。 – Dolphin 2010-01-28 15:08:19