user15192424
user15192424

Reputation:

Parse XML with XDocument C#

Please help. How to read from xml sub tree. I have xml doc:

<data>
<Infos>
    <Info>
        <AddressFk>1</AddressFk>
        <AddressLine1>1970</AddressLine1>
        <AddressLine2>Napa Ct.</AddressLine2>
            <Phone>
                <dataAsString1>111111</string>
                <dataAsString2>222222</string>
                <dataAsString3>333333</string>
            </Phone>
        <City>Bothell</City>
    </Info>
</Infos>

I read xml using XDocument:

XDocument xdoc = XDocument.Load("1.xml");
foreach (XElement addresList in xdoc.Document.Element("data").Elements("Infos").Elements("Info"))           
{
     address = new Address();
     address.id = (string)addresList.Element("AddressFk");
     address.Line1 = (string)addresList.Element("AddressLine1");
     address.Line2 = (string)addresList.Element("AddressLine2");
     address.City = (string)addresList.Element("City");
}

how to get the structure <Phone> ???

Upvotes: 1

Views: 60

Answers (1)

Genusatplay
Genusatplay

Reputation: 771

Use Elements

var phones = addresList.Element("Phone").Elements("string");
foreach(var phone in phones)
{
    Console.WriteLine((string)phone);
}

for the future, it is bad practice to use tag names with reserved words

Upvotes: 1

Related Questions