Domanda

I tried looking this up on here but couldnt find a proper answer. I have a XML string which has a bunch of nodes.
I want to extract only a couple of nodes from this string and append it with a new root element and return it.

I know how to do this by loading this onto an XMLDocument and selecting nodes. Is there a better way of doing this using an XpathNavigator or XmlReader?

This is my String

<root>
  <node1/>
  <node2/>
  <node3/>
  <node4/>
  <node5>
</root>

I want my output string to be

<root>
   <node3/>
   <node4/>
 </root>

Has to be done in an efficient manner.

È stato utile?

Soluzione

For the sake of simplicity, I would use XDocument.Parse(). And manipulate the DOM through the provided functions. Since the XML is provided as a string, probably small, I'm willing to bet that you will not see complexity problems.

If there are a lot of nodes to remove, I suggest you use a list of XPath strings. Then for each string, you can use doc.XPathSelectElements() to find all the elements and call remove() on each one. The resulting XDocument will have just the remaining nodes.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top