on 12-01-2011 9:16 AM
hi,
recently switch to java .
have a request to get a xml node values here -
I receive a String ojbect that have content like this:
<BookPost createStamp="20111201" fileType="Response" System="osMS" source="sAmazon" targetSystem="osMS" xmlns="http://">
<PostingResults>
<ref>11111</ref>
<error>wrong book isn</error>
</PostingResults>
<PostingResults>
<ref>22222</ref>
<error>wrong book author</error>
</PostingResults>
</BookPost >
I would like to print the value to system.out
<li> 11111 wrong book isn
<li> 22222 wrong book author
any idea how to reach this ? an example will be helped !
thanks a lot.
BenJ
Hi,
Convert the string to InputStream and parse it to get Document representation and then you can read the content of the xml tags.
Below is the snippet where xmlText is your String.
try{
InputStream inputStream = new ByteArrayInputStream(xmlText.getBytes("UTF-8"));
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
//Using DocumentBuilderFactory to get an instance of document builder
DocumentBuilder db = dbf.newDocumentBuilder();
//parse the inputStream using builder to get DOM representation of the String
Document dom = db.parse(inputStream);
NodeList listOfPostingResults = dom.getElementsByTagName("PostingResults");
int noOfPostingResults = listOfPostingResults.getLength();
for(int index = 0; index < noOfPostingResults ; index++){
Node firstPostingResultsNode = listOfPostingResults.item(index);
if(firstPostingResultsNode.getNodeType() == Node.ELEMENT_NODE){
Element firstPostingResultElement = (Element)firstPostingResultsNode;
NodeList refList = firstPostingResultElement.getElementsByTagName("ref");
Element refElement = (Element)refList.item(0);
NodeList refText = refElement.getChildNodes();
NodeList errorList = firstPostingResultElement.getElementsByTagName("error");
Element errorElement = (Element)errorList.item(0);
NodeList errorText = errorElement.getChildNodes();
wdComponentAPI.getMessageManager().reportSuccess("Ref: " + ((Node)refText.item(0)).getNodeValue().trim() +
" Error: "+((Node)errorText.item(0)).getNodeValue().trim());
}
}
}
catch (Exception e) {
wdComponentAPI.getMessageManager().reportException(e.toString());
}
Imports required:
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
For more info refer this link [http://www.developerfusion.com/code/2064/a-simple-way-to-read-an-xml-file-in-java/].
Regards,
Vishweshwara P.K.M.
You must be a registered user to add a comment. If you've already registered, sign in. Otherwise, register and sign in.
User | Count |
---|---|
93 | |
10 | |
10 | |
9 | |
9 | |
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.