cancel
Showing results for 
Search instead for 
Did you mean: 

Search a attribute value in a xml formated string ?

Former Member
0 Kudos

Hello everyone ,

I have a xml formated string . the inhalt is,

String xml = "


<version-data>
  <version-label/>
  <payload type="BF">
       <businessForm id="BFQuestion 1" BO="CAG_QUESTIONNAIRE"    guid="25057326DBA9B14DA7D1B145B4E97E2D" timestamp="2007-02-21T09:30:05.4210000" >
           <text spras="EN" text="aaa"/>
             ................................
 
      </businessForm>
  </payload>
</version-data>

";

i want to find the value of a attribute in this String.

e.g. guid="25057326DBA9B14DA7D1B145B4E97E2D"

i wanna get the value 25057326DBA9B14DA7D1B145B4E97E2D of attribute guid.

how can i do?

Thx in advance.

Regards.

Yaning

Accepted Solutions (0)

Answers (2)

Answers (2)

Former Member
0 Kudos

Two methods:

this one converts the xml string into a Document instance:

public static Document parse( String xmlString, boolean validate )

throws IOException, ParserConfigurationException, IOException, SAXException

{

DocumentBuilderFactory builderFactory =

DocumentBuilderFactory.newInstance();

builderFactory.setValidating( validate );

DocumentBuilder builder =

builderFactory.newDocumentBuilder();

return builder.parse( new InputSource( new StringReader( xmlString.trim() ) ) );

}

This one get the value based on its name:

public static String getNodeValue( Node root, String name ) {

String nodeValue = null;

if ( root.hasAttributes() ) {

Node valueNode = root.getAttributes().getNamedItem( name );

if ( valueNode != null ) {

nodeValue = valueNode.getNodeValue();

}

}

if ( nodeValue == null ) {

NodeList nodes = root.getChildNodes();

for (int i=0 ; i<nodes.getLength() ; i++ ) {

if ( nodes.item( i ).getNodeName().equalsIgnoreCase( name ) ) {

return nodes.item( i ).getNodeValue();

}

}

}

return nodeValue;

}

Dennis

Vlado
Advisor
Advisor
0 Kudos

Hi Yaning,

You can build a DOM tree from that String and traverse the Document. You could also utilize XPath and/or XSLT. Googling for this will give you lots of examples.

HTH!

-Vladimir