Piscean
Piscean

Reputation: 3079

Whats the best way to remove same tags from an xml string?

In my android app, I am getting following xml string from host:

 <response>
     <objects>
         <object>
              <id>1</id>
              <name>Black</name>
              <desc>Black color</desc>
         </object>
         <object>
              <id>2</id>
              <name>White</name>
              <desc>White color</desc>
         </object>
         ...
         ...
         <object>
              <id>99</id>
              <name>Green</name>
              <desc>Green color</desc>
         </object>
     </objects>
 </response>

Its a string and i want to remove all desc tags from string. What is the best and easiest way to do that? Thanks in advance.

Upvotes: 1

Views: 538

Answers (3)

Martin
Martin

Reputation: 630

I think this will work.

String modifiedXmlString = xmlString.replaceAll("(?s)<desc>.*?</desc>","");

This use regular expression to remove the xml tag you want. You can read more about regular expression here http://docs.oracle.com/javase/7/docs/api/java/util/regex/Pattern.html

Upvotes: 1

keshlam
keshlam

Reputation: 8058

"Best and easiest" is an opinion question.

It'd be pretty straightforward to modify one of the many examples of using the JAXP APIs to parse this document, find and discard those tags (and, presumably, their content), and output the modified document.

It'd also be pretty straightforward to write an XSLT stylesheet that did this. Start with the "identity transform", then add

<xsl:template match="desc"/>

... in other words, when you reach a <desc> element, do nothing rather than copying it to the output.

And in this particular case, the "Desperate Perl Hacker" approach would work -- that is, you could simply process this as a text file and discard/delete lines containing .

Upvotes: 2

Qwerky
Qwerky

Reputation: 18445

Presumably you have your XML parsed as a document? You could get all the nodes using, lets say XPath, then call getParentNode().removeChild(node) on each node.

Upvotes: 0

Related Questions