1

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

5
  • Welcome @JeriKo, are you sure that your XML phone part is right?! Commented Mar 28, 2021 at 12:26
  • Yes, he is exactly like that. I didn't create it, I only need to read it. Commented Mar 28, 2021 at 12:32
  • tag names are <string> ?! Commented Mar 28, 2021 at 12:33
  • @UsemeAlehosaini: That's entirely valid XML, as far as I'm aware... Commented Mar 28, 2021 at 13:01
  • @JonSkeet thank you, many times I parsed XMLs generated by different sources but never saw reserved keyword as tag name, it is just new for me :) thanks again. Commented Mar 28, 2021 at 13:33

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

2 Comments

"it is bad practice to use tag names with reserved words" - it's really not. XML document designers shouldn't feel constrained by the keywords in all the various different programming languages. Any XML API that finds it difficult to handle element or attribute names that happen to be reserved in the language of that API is badly designed, IMO. I can see if causing issues for code generators which might want to generate models based on the XML, but that feels like something the code generators should just handle, to my mind.
(Not that I'm saying that <string> is a particularly good element name in this particular case, but only because it's not really descriptive, rather than because it's a reserved word.)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.