0

I have an xml that looks like this:

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

1 Answer 1

1

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

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;

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

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

linq

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;
Sign up to request clarification or add additional context in comments.

1 Comment

what if i want to get the value of version in the size node if the whistle type is red? Check out the edit.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.