I have an XElement object that was created by parsing the XML from a word document. What I want to do is find and remove a specific node that I am trying to find using LINQ.
The XML is a couple hundred lines long so I don’t want to post the whole thing here, I will just show the first 20 lines:
<w:body xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main">
<w:p w:rsidR="00CB3A3E" w:rsidP="00257CF7" w:rsidRDefault="008C1E91">
<w:pPr>
<w:pStyle w:val="Heading-Title" />
</w:pPr>
<w:r>
<w:t>References</w:t>
</w:r>
</w:p>
<w:sdt>
<w:sdtPr>
<w:alias w:val="Client" />
<w:tag w:val="ClientName" />
<w:id w:val="-1008363323" />
<w:lock w:val="contentLocked" />
<w:placeholder>
<w:docPart w:val="DefaultPlaceholder_1082065158" />
</w:placeholder>
<w:dataBinding w:xpath="/project[1]/ClientName[3]" w:storeItemID="{1BDA6E50-A0B2-47FF-9929-1F045B6CF8AD}" />
<w:text />
The node I want to remove is : <w:t>References</w:t> . I am currently getting a “Sequence contains no elements" exception. newBody is the XElement.
newBody.Descendants.Where(Function(e) e.Name.Equals("<w:t>") AndAlso e.Value.Equals("References")).First().Remove()
As I said I am getting the exception noted above. Is this how I should be attempting to get to this node? Is there a better way? Why is my query not getting the specified node? ANy advice on how to do this better is very much appreciated, I’m still trying to learn best practices when it comes to XML traversal in .net and LINQ itself. Thanks much!!
I’m making a little bit of a guess here since this is VB.net and I come from a C# background, but the LINQ part looks the same. I think your problem lies with the
Name.Equals("<w:t>")part.Nameis not a string but anXNameand it has a few more properties. Most likely you need to look atName.LocalName.Equals("t"):As for the second part of your question, if you just want to remove one node, then navigating to that one specific node is most likely far more efficient than making a document global rule to which only one node matches. My approach to you problem would be more like this: