user3745020
user3745020

Reputation: 81

Get XML attribute Values by its Descendants

I have an XML in this Format and I want to get List of Line ID and its Name

<ArrayOfLines xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
    <LineStatus ID="0" StatusDetails="">
        <BranchDisruptions />
        <Line ID="1" Name="Line1" />
        <Status ID="GS" CssClass="GoodService" Description="Good Service" IsActive="true">
            <StatusType ID="1" Description="Line" />
        </Status>
    </LineStatus>
    <LineStatus ID="1" StatusDetails="">
        <BranchDisruptions />
        <Line ID="2" Name="Line2" />
        <Status ID="GS" CssClass="GoodService" Description="Good Service" IsActive="true">
            <StatusType ID="1" Description="Line" />
        </Status>
    </LineStatus>
</ArrayOfLines>

and This is the code I have written:

String xmlFilePath = @"C:/myXML.xml";
XDocument xmlFile = XDocument.Load(xmlFilePath);
var query = from c in xmlFile.Descendants("LineStatus") select c;

but it is not returning me any results.

Upvotes: 0

Views: 619

Answers (3)

Tony Stark
Tony Stark

Reputation: 771

Try this...

String xmlFilePath = @"C:/myXML.xml";
XDocument xmlFile = XDocument.Load(xmlFilePath);
var query = (from c in xmlFile.Descendants("Line") 
             select new { 
                          ID=c.Attribute("ID").Value,
                          Name=c.Attribute("Name").Value
                        }).ToList();;

Upvotes: 0

Sowiarz
Sowiarz

Reputation: 1081

Here is my idea but you have to create list "namesList" and "idList" before. Try this:

XDocument xDoc = XDocument.Load("your xml file");
foreach (var elem in xDoc.Document.Descendants("line"))
{
    idList.Add(elem.Attribute("ID").Value);
    namesList.Add(elem.Attribute("Name").Value);
}

And you have full controll by index of each list to this data. After that you can also create object of these 2 elements

Upvotes: 2

Selman Gen&#231;
Selman Gen&#231;

Reputation: 101711

You have an xml namespace, you need to specify it with element names:

XNamespace ns = "http://www.w3.org/2001/XMLSchema-instance";
var query = from c in xmlFile.Descendants(ns + "LineStatus") select c;

Upvotes: 0

Related Questions