on 02-21-2007 10:31 AM
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
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
You must be a registered user to add a comment. If you've already registered, sign in. Otherwise, register and sign in.
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
You must be a registered user to add a comment. If you've already registered, sign in. Otherwise, register and sign in.
User | Count |
---|---|
80 | |
9 | |
9 | |
7 | |
7 | |
7 | |
6 | |
5 | |
5 | |
4 |
You must be a registered user to add a comment. If you've already registered, sign in. Otherwise, register and sign in.