我有一个如下所示的xml:
<ProductTemplate ProductName="FlamingoWhistle" Version="1.8.02" >
<Whistle Type="Red" Version="3.0.5" />
<Size Type="Large" Version="1.0" />
<Whistle Type="Blue" Version="2.4.3" />
</ProductTemplate> 如何检查类型是否等于红色,返回该类型的版本?
这是我尝试过的,但如果元素不是第一个,它就失败了。
XElement root = XElement.Load(path);
if (XPathSelectElement("Whistle").Attribute("Type") == "Blue")
{
Console.WriteLine(XPathSelectElement("Whistle").Attribute("Version").value));
}
else
{
Console.WriteLine("Sorry, no FlamingoWhistle in that color");
}发布于 2014-07-24 14:09:21
这应该能起作用
foreach(XElement xe in root.Elements("Whistle"))
{
if (xe.Attribute("Type").Value == "Red")
{
Console.WriteLine(xe.Attribute("Version").Value);
}
}使用linq
string version = root.Elements("Whistle")
.Where(x => x.Attribute("Type").Value == "Red")
.First().Attribute("Version").Value;xpath
string version = root.XPathSelectElement("Whistle[@Type='Red']").Attribute("Version").Value;更新
首先,您可能需要为属性层次结构更正xml,在您当前的xml元素大小中,它不是哨子。我想是那个孩子
<ProductTemplate ProductName="FlamingoWhistle" Version="1.8.02">
<Whistle Type="Red" Version="3.0.5">
<Size Type="Large" Version="1.0" />
</Whistle>
<Whistle Type="Blue" Version="2.4.3" />
</ProductTemplate>从size元素检索版本
foreach (XElement xe in root.Elements("Whistle"))
{
if (xe.Attribute("Type").Value == "Red")
{
Console.WriteLine(xe.Element("Size").Attribute("Version").Value);
}
}林克
string version = root.Elements("Whistle")
.Where(x => x.Attribute("Type").Value == "Red")
.First().Element("Size").Attribute("Version").Value;xpath
string version = root.XPathSelectElement("Whistle[@Type='Red']/Size").Attribute("Version").Value;https://stackoverflow.com/questions/24935904
复制相似问题