Search code examples
c#xmlattributes

How to get an xml value depending on node attribute in C#?


Let's say we have the following xml :

<?xml version="1.0" encoding="UTF-16"?>
<OrderExchangeMessage version="9.0" type="AddOrder"
    xmlns:xs="xxx"
    xmlns:xsi="xxx"
    xmlns="xxx">
    <Command>
        <AddOrderRequest>
            <Order>
                <OrderID>xxx</OrderID>
                <InnerOrder>
                    <RestorationOrder version="5.0">
                        <ModelElements>
                            <ModelElement displayName="red car">
                                <files>
                                    <file path="pathtofile"/>
                                </files>
                            </ModelElement>
                            <ModelElement displayName="red truck">
                                <files>
                                    <file path="pathtofile"/>
                                </files>
                            </ModelElement>
                            <ModelElement displayName="green car">
                                <files>
                                    <file path="pathtofile"/>
                                </files>
                            </ModelElement>
                        </ModelElements>
                    </RestorationOrder>
                </InnerOrder>
            </Order>
        </AddOrderRequest>
    </Command>
</OrderExchangeMessage>

How can I retrieve the value of file path only if the attribute of ModelElement contains "red" ?

So I need to know which file goes for a red car and which file for a red truck.

I also tried to get a parent in order to look for child, but got no luck so far.

XmlNodeList? nodeListItems = xmldoc.SelectNodes("/OrderExchangeMessage[@version='9.0']/" +
                                                                    "Command/AddOrderRequest/Order/InnerOrder/" +
                                                                    "RestorationOrder[@version='5.0']/" +
                                                                    "ModelElements");

Solution

  •     XmlDocument doc = new XmlDocument();
        doc.LoadXml(xml);
        
        XmlNodeList modelElements = doc.GetElementsByTagName("ModelElement");
        foreach (XmlNode modelElement in modelElements)
        {
            XmlNode displayName = modelElement.Attributes.GetNamedItem("displayName");
            if (displayName != null && displayName.Value.Contains("red"))
            {
                XmlNode path = modelElement["files"]["file"].Attributes.GetNamedItem("path");
                Console.WriteLine(path.Value);
            }
        }
    

    This should do the trick.

    xml is the xml document

    This code iterates all ModelElement and Checks displayName for the value of red