demo demo demo

xml child element node or attribute value

106 Views Asked by At

I have a xml schema with nested xml elements and following is the small piece of that

<aa>
    <id extension="xx" root="56" />
    <name>demo</name>
    <telecom use="emer" value="tel:34444" />
</aa>

<bb>
   <value value="12345" />
</bb>
<cc>
   <value value="234567" />
</cc>

From this, I have to get the value of "name tag" under "aa tag", last attribute (tel:) of telecom tag, and attribute value of the "value tag" (which is found under bb tag and cc tag)

I tried the following code, but it's not getting exactly what I am expecting.

xDoc.Descendants().Where(x => x.Name.LocalName.Equals("aa")
                              || x.Name.LocalName.Equals("telecom") && 
                              (x.FirstAttribute.Equals("EC")
                               || x.Name.LocalName.Equals("bb")
                               || x.Name.LocalName.Equals("cc"))

Please provide the solution for this issue.

1

There are 1 best solutions below

4
er-sho On BEST ANSWER

You need to select the appropriate descendant of each of your value and then by using proper linq query you can select desired values

class Program
{
    public static void Main(string[] args)
    {
        XDocument doc = XDocument.Load(@"Path to your xml file");

        var name = doc.Descendants("organisation").Elements().Where(x => x.Name == "name").Select(x => (string)x).FirstOrDefault();
        var tel = doc.Descendants("organisation").Elements().Where(x => x.Name == "telecom").Select(x => x.Attribute("value").Value).FirstOrDefault();
        var bb_value = doc.Descendants("startdate").Elements().Where(x => x.Name == "value").Select(x => x.Attribute("value").Value).FirstOrDefault();
        var cc_value = doc.Descendants("enddate").Elements().Where(x => x.Name == "value").Select(x => x.Attribute("value").Value).FirstOrDefault();

        Console.WriteLine($"name: {name} \ntel: {tel} \nbb_value: {bb_value} \ncc_value: {cc_value}");
        Console.ReadLine();
    }
}

Output:

enter image description here