简体   繁体   中英

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> ???

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

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