0

I have a XML read into a one single String. I need to get all the data inside <code> tags. I do not need to go though whole XML file parsing them. Can i use a simple string processing technique to get the data inside those tags.

input : <a><b><code>Hello</code></b><code>World</code></a>

output : Hello, World
3
  • If that syntax is always the same or very regular you can probably use regular expressions. But it's way safer if you use some real XML processing like jondev.net/articles/Android_XML_SAX_Parser_Example Commented Mar 15, 2012 at 11:24
  • can you suggest how to create a regular expression for above? and how to call it? Thank you Commented Mar 15, 2012 at 11:25
  • 1
    see here stackoverflow.com/questions/335250/… "<code>(.*?)</code>" would match your code tags and matcher.group(1) would contain the text. But be aware that this is not going to work (or needs way more complicated regexes) if the xml could be like < code attribute="something"> or can contain <code> or other tags inside <code> etc. XML is not a regular language so there are cases that can't be done with regular expressions. Commented Mar 15, 2012 at 11:54

2 Answers 2

3

Regex is not an advisable tool to play with XML, specially when there are sophiticated many parsers are there. You may use javax.xml.xpath package to do this stuff for you like:

    XPath xp = XPathFactory.newInstance().newXPath();
    NodeList nl =  (NodeList)xp.evaluate("//code", new InputSource(new StringReader("<a><b><code>Hello</code></b><code>World</code></a>")), XPathConstants.NODESET);
    for(int i=0; i< nl.getLength(); i++){
        System.out.print(nl.item(i).getTextContent()+", ");
    }

will result

Hello, World, 
Sign up to request clarification or add additional context in comments.

Comments

0

Follow the example here: it's simple.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.