0

I have a program that builds XML line by line pulling the content from MS Word docs. The XML can contain nested bullet lists like that shown below. I need the ability to be able to specify which list level my item needs to be inserted. So this could be the final nested bullet list (lists within a list).

<bulletlist>
    <item>Level 1 item</item>
    <item>Level 1 item:
        <bulletlist>
            <item>Level 2 item</item>
            <item>Level 2 item
                <bulletlist>
                    <item>Level 3 item</item>
                    <item>Level 3 item</item>
                    <item>Level 3 item</item>
                </bulletlist>
            </item>
        </bulletlist>
    </item>
    <item>Level 1 item</item>
    <item>Level 1 item</item>
</bulletlist>

Now to get here, my program would look at the paragraph indent in Word, identify which list level it is, and then build the XML structure. So if I just wanted to add another item to the current Level 1, i would just go..

content.Descendants("item")
                .LastOrDefault()
                .AddAfterSelf(new XElement("item", "some new text to go here"));

But let's assume i have this XML fragment bullet list:

<bulletlist>
    <item>Level 1 item</item>
    <item>Level 1 item:
        <bulletlist>
            <item>Level 2 item</item>
            <item>Level 2 item
                <bulletlist>
                    <item>Level 3 item</item>
                    <item>Level 3 item</item>
                    <item>Level 3 item</item>
                </bulletlist>
            </item>
        </bulletlist>
    </item>
</bulletlist>

and i now need to add another item to the Level 1 list. I cannot use the same code as above as it will just add it to the Level 3 list.

I need to specify which list level i need to add it to without identifying the XML in any way. Some kind of way of using an index as opposed to lastOrDefault() or something like that. Any ideas?

Daedalus
  • 539
  • 2
  • 6
  • 16
  • You can't use xml linq when you have an error in the xml like in the second example. No Net Library Xml method will allow a corrupted xml to be parsed. – jdweng May 16 '19 at 18:35
  • You can use `XElementExtensions.DescendantsUntil()` from [this answer](https://stackoverflow.com/a/46016931/3744182) to [How to find highest level descendants with a given name](https://stackoverflow.com/q/46007738/3744182) to find all topmost `` descendants. In fact I think this is a duplicate, agree? – dbc May 16 '19 at 22:42

0 Answers0