0

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.

Vijay V
  • 389
  • 5
  • 11
  • 23
  • So you want to remove nodes 1, 3, and 5? – user845279 Jun 20 '12 at 00:01
  • yes but in reality I might have to remove more nodes. I guess what I mean to say is, there could be more than a total of 5 nodes out of which I need only 2. Also my input is a string (i know i mentioned this in my post, just emphasizing) – Vijay V Jun 20 '12 at 00:44

1 Answers1

0

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.

user845279
  • 2,794
  • 1
  • 20
  • 38
  • thanks for the answer. however even though I get the XDocument part, what method(s) would I use to achieve what I want? – Vijay V Jun 20 '12 at 13:34
  • this is what I tried, but it deletes everything except for the root XDocument x = XDocument.Parse(xmlstring); x.Root.Elements().Where(e => e.Name != "node3" || e.Name != "node4").Remove(); – Vijay V Jun 20 '12 at 13:59
  • Can I ask more question here or do I have to open another forum. (I want to add attributes to based on ) – Vijay V Jun 20 '12 at 17:04
  • You should open another question to get detailed help. But the general idea is to select both elements then call `setAttributeValue()` on node3. – user845279 Jun 20 '12 at 17:35