I'm trying to load a Unsorted List
from XML file
.
The parents tags must be loaded into ul
and children tags into ol
.
The problem is, i can't get the parent alone, it always print the parent value and its children.
XML file:
<Sections>
<Section id="D2F4CD35-FB7A-4E24-9CC3-7C2095D1A2D5">
<![CDATA[ <PARENT 1> ]]>
<SubSection>
<![CDATA[ <CHILED 1.1> ]]>
</SubSection>
<SubSection>
<![CDATA[ <CHILED 1.2> ]]>
</SubSection>
</Section>
<Section id="CF7F2212-A4DB-47AA-8129-61AF2F930C2C">
<![CDATA[ <PARENT 2> ]]>
<SubSection>
<![CDATA[ <CHILED 2.1> ]]>
</SubSection>
<SubSection>
<![CDATA[ <CHILED 2.2> ]]>
</SubSection>
</Section>
</Sections>
C# code:
XDocument xmlDoc = XDocument.Load("C:/SectionXmlFile.xml");
var parents = xmlDoc.Element("Sections");
if (parents != null) {
foreach (var parent in parents.Descendants("Section")) {
<ul>@parent.Value</ul>
foreach (var child in parent.Descendants("SubSection")) {
<ol>@child.Value</ol>
}
}
}
Result:
<PARETN 1> <CHILED 1.1> <CHILED 1.2>
<CHILED 1.1>
<CHILED 1.2>
<PARETN 2> <CHILED 2.1> <CHILED 2.2>
<CHILED 2.1>
<CHILED 2.2>
Expected result:
<PARETN 1>
<CHILED 1.1>
<CHILED 1.2>
<PARETN 2>
<CHILED 2.1>
<CHILED 2.2>
I suspect this is the problem:
<ul>@parent.Value</ul>
That's closing the <ul>
tag, rather than including each of the child elements within it.
The reason you're getting the CHILED
elements twice is that you're using XElement.Value
which is finding all the text nodes under the parent. You only want the immediate child text nodes.
I suspect you may want:
foreach (var parent in parents.Descendants("Section")) {
<ul>@(parent.Nodes().OfType<XText>().First().Value)
foreach (var child in parent.Descendants("SubSection")) {
<ol>@child.Value</ol>
}
</ul>
}
(At least conceptually - the razor syntax may be slightly off...)
That way of finding the first text node is admittedly rather irritating. If you could change your XML that would make it easier (e.g. make each Section
element have a Title
element with just the right title text, or whatever) but failing that I think you're left with something like I've outlined above.
It's also unclear why you're starting new lists rather than having list items, but that's a different matter...
See more on this question at Stackoverflow