简体   繁体   中英

XML parsing in C#

I do have the following xml response:

<?xml version="1.0" encoding="UTF-8"?>
<UDSObjectList>
<UDSObject>
    <Handle>zLanguage:400001</Handle>
    <Attributes>
        <Attribute DataType="2001">
            <AttrName>id</AttrName>
            <AttrValue>400001</AttrValue>
        </Attribute>
        <Attribute DataType="2002">
            <AttrName>LngCode</AttrName>
            <AttrValue>deu</AttrValue>
        </Attribute>
    </Attributes>
</UDSObject>
<UDSObject>
    <Handle>zLanguage:400002</Handle>
    <Attributes>
        <Attribute DataType="2001">
            <AttrName>id</AttrName>
            <AttrValue>400002</AttrValue>
        </Attribute>
        <Attribute DataType="2002">
            <AttrName>LngCode</AttrName>
            <AttrValue>eng</AttrValue>
        </Attribute>
    </Attributes>
</UDSObject>
</UDSObjectList>

How can I get the AttrValue value based on the AttrName value?

For example, when the attribute name equal "id", I need to get its corresponding attribute value which is 400001 or 400002 in the previous response. Another example, when the attribute name equal "LngCode", I need to get its corresponding attribute value which is eng or deu in the previous response!

Thanks in advance

Here is a sample code;

    string myFilter = "LngCode";
    var xDoc = XDocument.Load(@"C:\temp.xml");
    var elements = xDoc.Descendants("AttrName")
        .Where(d => d.Value.Equals(myFilter))
        .Select(d => d.ElementsAfterSelf().FirstOrDefault());

    foreach (var element in elements)
    {
        Console.WriteLine(element.Value);
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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