c# - Read XDocument same name elements using foreach -
i have xml file:
<encounter type="type1"> <strings> <text>text1</text> <text>text2</text> <text>text3</text> </strings> </encounter> idea set values of text elements list if "type" attribute correct. code is:
foreach (xelement el in xdoc.root.elements()) { if(el.attribute("type").value == choice) { list<string> textstrings = new list<string>(); foreach (xelement elstr in el.element("strings")) { textstrings.add(elstr.element("text").value); } break; } } part attribute working, read several elements wits same name tricky me.
you need foreach:
foreach (xelement elstr in el.element("strings")) { foreach(xelement eltext in elstr.elements("text")) { textstrings.add((string)eltext); } } or create more clear:
list<string> textstrings = xdoc.root .elements() .first(x => (string)x.attribute("type") == choice) .element("strings") .elements("text"). .select(t => (string)t) .tolist(); c# xml foreach linq-to-xml
No comments:
Post a Comment