简体   繁体   English

如何获取XML节点值

[英]How to get XML node values

I have an xml that looks like this: 我有一个看起来像这样的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>  

How can I check if type equals red, return the version for that type? 如何检查类型是否等于红色,返回该类型的版本?
This is what I have tried but fails if the element isn't first 这是我尝试过的方法,但是如果该元素不是第一个则失败

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");
}

this should do the trick 这应该可以解决问题

foreach(XElement xe in root.Elements("Whistle"))
{
    if (xe.Attribute("Type").Value == "Red")
    {
        Console.WriteLine(xe.Attribute("Version").Value);
    }
}

use linq 使用LINQ

string version = root.Elements("Whistle")
                 .Where(x => x.Attribute("Type").Value == "Red")
                 .First().Attribute("Version").Value;

xpath XPath的

string version = root.XPathSelectElement("Whistle[@Type='Red']").Attribute("Version").Value;

update 更新

first of all you may need to correct the xml for property hierarchy, in your current xml element Size is not a child of Whistle. 首先,您可能需要为属性层次结构更正xml,因为当前的xml元素Size不是Whistle的子级。 i assume it to be the child 我认为这是孩子

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

retrieving the version from size element 从size元素检索版本

foreach (XElement xe in root.Elements("Whistle"))
{
    if (xe.Attribute("Type").Value == "Red")
    {
        Console.WriteLine(xe.Element("Size").Attribute("Version").Value);
    }
}

linq LINQ

string version = root.Elements("Whistle")
     .Where(x => x.Attribute("Type").Value == "Red")
     .First().Element("Size").Attribute("Version").Value;

xpath XPath的

string version = root.XPathSelectElement("Whistle[@Type='Red']/Size").Attribute("Version").Value;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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