I have an XML string got as a response. But I am unable to reach at Response Code and remarks. Can anybody help me to get the response code.
<s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/">
<s:Body>
<GetIMEIInfoResponse xmlns="http://tempuri.org/">
<GetIMEIInfoResult>
<![CDATA[
<SerialsDetail>
<Item>
<ResponseCode>2</ResponseCode>
<Remark>Invalid Input</Remark>
</Item>
</SerialsDetail>
]]>
</GetIMEIInfoResult>
</GetIMEIInfoResponse>
</s:Body>
</s:Envelope>
Thats how I am trying to do
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder;
try {
builder = factory.newDocumentBuilder();
Document doc = builder.parse(new InputSource(new StringReader(response)));
NodeList list = doc.getElementsByTagName("Remark");
System.out.println(list.getLength());
Node n = list.item(0);
System.out.println(n.getTextContent());
} catch (Exception e) {
e.printStackTrace();
}
You are asking for an element with name "Remark", but you document does not contain such an element. Instead, it contains only an "GetIMEIInfoResult" element with a bunch of text in it. This text happens to be xml. But in order to access the contents of the inner piece of XML, you have to parse the contents of the "GetIMEIInfoResult" in the same way that you've parsed the entire document.
Here is how you can do it:
import java.io.*;
import javax.xml.parsers.*;
import org.w3c.dom.*;
import org.xml.sax.InputSource;
public class NestedCDATA {
private static String response =
"<s:Envelope xmlns:s=\"http://schemas.xmlsoap.org/soap/envelope/\">" +
" <s:Body>" +
" <GetIMEIInfoResponse xmlns=\"http://tempuri.org/\">" +
" <GetIMEIInfoResult>" +
" <![CDATA[" +
" <SerialsDetail>" +
" <Item>" +
" <ResponseCode>2</ResponseCode>" +
" <Remark>Aawwwwwwww yeaaaah!</Remark>" +
" </Item>" +
" </SerialsDetail>" +
" ]]>" +
" </GetIMEIInfoResult>" +
" </GetIMEIInfoResponse>" +
" </s:Body>" +
"</s:Envelope>";
public static String getCdata(Node parent) {
NodeList cs = parent.getChildNodes();
for(int i = 0; i < cs.getLength(); i++){
Node c = cs.item(i);
if(c instanceof CharacterData) {
CharacterData cdata = (CharacterData)c;
String content = cdata.getData().trim();
if (content.length() > 0) {
return content;
}
}
}
return "";
}
public static void main(String[] args) {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder;
try {
builder = factory.newDocumentBuilder();
Document doc = builder.parse(new InputSource(new StringReader(response)));
Node cdataParent = doc.getElementsByTagName("GetIMEIInfoResult").item(0);
DocumentBuilder cdataBuilder = factory.newDocumentBuilder();
Document cdataDoc = cdataBuilder.parse(new InputSource(new StringReader(
getCdata(cdataParent)
)));
Node remark = cdataDoc.getElementsByTagName("Remark").item(0);
System.out.println("Content of Remark in CDATA: " + getCdata(remark));
} catch (Exception e) {
e.printStackTrace();
}
}
}
Result: "Content of Remark in CDATA: Aawwwwwwww yeaaaah!".
Here is another interesting question for you: why does your service output XML with XML in it? XML all by itself is already nested enough. Is it really necessary to wrap parts of it in CDATA?
The problem of the XML is that the data in the tag GetIMEIInfoResult is CDATA. This causes the builder not to recognize it as XML. To access the data in the tag GetIMEIInfoResult you can use the following:
Element infoResult = (Element) list.item(0);
String elementData = getCharacterDataOfNode(infoResult.getFirstChild());
public static String getCharacterDataOfNode(Node node) {
String data = "";
if (node instanceof CharacterData) {
data = ((CharacterData) node).getData();
}
return data;
}
Then you have to parse that data again with a DocumentBuilder where you can access the tag Remark. To get the content you have again work with the getCharacterDataOfNode() method.
Related
Consider this example
#Test
public void testXML() {
final String s = "<?xml version=\"1.0\" encoding=\"UTF-8\"?><results>\n" +
" <status>OK</status>\n" +
" <usage>By accessing AlchemyAPI or using information generated by AlchemyAPI, you are agreeing to be bound by the AlchemyAPI Terms of Use: http://www.alchemyapi.com/company/terms.html</usage>\n" +
" <url/>\n" +
" <language>english</language>\n" +
" <docSentiment>\n" +
" <type>neutral</type>\n" +
" </docSentiment>\n" +
"</results> ";
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder;
try
{
builder = factory.newDocumentBuilder();
Document doc = builder.parse( new InputSource( new StringReader( s ) ) );
System.out.println(doc.toString());
} catch (Exception e) {
e.printStackTrace();
}
}
When I run this example
System.out.println(doc.toString()); turns out to be [#document: null].
I also validated this XML online and no errors were found. What am I missing?
What I need?
I need to find out value of <docSentiment> in this XML
Thanks
As per MadProgrammer's advice, I managed to get the value.
Note: Even though [#document: null] was shown, the document was not null, in reality.
#Test
public void testXML() {
final String s = "<?xml version=\"1.0\" encoding=\"UTF-8\"?><results>\n" +
" <status>OK</status>\n" +
" <usage>By accessing AlchemyAPI or using information generated by AlchemyAPI, you are agreeing to be bound by the AlchemyAPI Terms of Use: http://www.alchemyapi.com/company/terms.html</usage>\n" +
" <url/>\n" +
" <language>english</language>\n" +
" <docSentiment>\n" +
" <type>neutral</type>\n" +
" </docSentiment>\n" +
"</results>";
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder;
try
{
builder = factory.newDocumentBuilder();
Document doc = builder.parse( new InputSource( new StringReader( s ) ) );
XPathFactory xPathfactory = XPathFactory.newInstance();
XPath xpath = xPathfactory.newXPath();
XPathExpression expr = xpath.compile("//docSentiment/type");
NodeList nl = (NodeList) expr.evaluate(doc, XPathConstants.NODESET);
System.out.println("Sentiment:" + ((DTMNodeList) nl).getDTMIterator().toString());
} catch (Exception e) {
e.printStackTrace();
}
}
and I go the output as
Sentiment:neutral
input file
xml
<?xml version="1.0" encoding="UTF-8"?>
<response>
<message></message>
<messagecode></messagecode>
<messagedescription></messagedescription>
</response>
<response>
<message></message>
<messagecode></messagecode>
<messagedescription></messagedescription>
</response>
two response --
response id root node..
Java code
public void readXML(String output) {
try {
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
Document doc = dBuilder.parse(output);
doc.getDocumentElement().normalize();
NodeList nodes = doc.getElementsByTagName("response");
for (int i = 0; i < nodes.getLength(); i++) {
Node nNode = nodes.item(i);
if (nNode.getNodeType() == Node.ELEMENT_NODE) {
Element element = (Element) nNode;
NodeList msg = element.getElementsByTagName("message");
Element line = (Element) msg.item(i);
System.out.println("Message: " + getCharacterDataFromElement(line));
NodeList msgcode = element.getElementsByTagName("messagecode");
line = (Element) msgcode.item(i);
System.out.println("Message Code: " + getCharacterDataFromElement(line));
NodeList msgdes = element.getElementsByTagName("messagedescription");
line = (Element) msgdes.item(i);
System.out.println("Message Description: " + getCharacterDataFromElement(line));
NodeList medialink = element.getElementsByTagName("medialink");
line = (Element) medialink.item(i);
System.out.println("Media link: " + getCharacterDataFromElement(line));
NodeList mediastatus = element.getElementsByTagName("mediastatus");
line = (Element) mediastatus.item(i);
System.out.println("Media Status: " + getCharacterDataFromElement(line));
}
}
} catch (ParserConfigurationException e) {
e.printStackTrace();
} catch (SAXException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
public static String getCharacterDataFromElement(Element e) {
Node child = e.getFirstChild();
if (child instanceof CharacterData) {
CharacterData cd = (CharacterData) child;
return cd.getData();
}
return "";
}
i try this code but error will display how can i reslove this....
SAX Exception will give error in not well formed xml file.
how can i read two root node values in same java file..
Your XML does not have matching opening/closing tags or a root node.
Something like this would suffice:
<?xml version="1.0" encoding="UTF-8"?>
<responses>
<response>
<message></message>
<messagecode></messagecode>
<messagedescription></messagedescription>
</response>
<response>
<message></message>
<messagecode></messagecode>
<messagedescription></messagedescription>
</response>
</responses>
XML should always be well-formed, meaning that it has only one root node and every opening tag should have a closing tag. Check for correct XML syntax from W3Schools pages: http://www.w3schools.com/xml/xml_syntax.asp There are also lot's of other useful information about constructing XML documents there.
If then for some reason you absolutely need to handle XML with multiple root nodes, then it's probably manual parsing with substrings or regular expressions, which i don't recommend.
Either way, if you can do something about it, try to form the XML so that you have only one root node. Period.
Hye I am new to read XML File using Java my problem is that I have been trying to read an xml and between a specific tag I want to get the required data I am using XPath and my query is:
String expression = "/ADOXML/MODELS/MODEL/MODELATTRIBUTES/ATTRIBUTE[#type='STRING']";
It works fine and my specific Tag to read from is:
<ATTRIBUTE name="Description" type="STRING"> SOME TEXT </ATTRIBUTE>
But I want to read the data inside only these types of Tags so that my output should be:
SOME TEXT
inside the tag!
can somebody help me how can I do this Please I am new to xml reading! Trying my best as:
String expression = "/ADOXML/MODELS/MODEL/MODELATTRIBUTES/ATTRIBUTE[#name='Description' and ./type/text()='STRING']";
But it wont give me any output!
thanks in advance
My Code:
DocumentBuilderFactory builderFactory =
DocumentBuilderFactory.newInstance();
DocumentBuilder builder = null;
try {
builder = builderFactory.newDocumentBuilder();
org.w3c.dom.Document document = builder.parse(
new FileInputStream("c:\\y.xml"));
XPath xPath = XPathFactory.newInstance().newXPath();
String expression = "/ADOXML/MODELS/MODEL/MODELATTRIBUTES/ATTRIBUTE[#name='Description'and #type='STRING']";
System.out.println(expression);
NodeList nodeList = (NodeList) xPath.compile(expression).evaluate(document, XPathConstants.NODESET);
for (int i = 0; i < nodeList.getLength(); i++) {
System.out.println(nodeList.item(i).getFirstChild().getNodeValue());
}
} catch (ParserConfigurationException | SAXException | IOException e) {
System.out.print(e);
}
There is a problem with my code cant figure out what!
This code works fine for me with the changed XPath to:
"/ADOXML/MODELS/MODEL/MODELATTRIBUTES/ATTRIBUTE[#name='Description'][#type='STRING']":
private static final String EXAMPLE_XML =
"<?xml version=\"1.0\" encoding=\"UTF-8\"?>" +
"<ADOXML adoversion=\"Version 5.1\" username=\"kvarga\" database=\"adonisdb\" time=\"08:55\" date=\"30.11.2013\" version=\"3.1\">" +
"<MODELS>" +
"<MODEL version=\"\" applib=\"ADONIS BPMS BP Library 5.1\" libtype=\"bp\" modeltype=\"Business process model\" name=\"Product development\" id=\"mod.25602\">" +
"<MODELATTRIBUTES>" +
"<ATTRIBUTE name=\"Version number\" type=\"STRING\"> </ATTRIBUTE>" +
"<ATTRIBUTE name=\"Author\" type=\"STRING\">kvarga</ATTRIBUTE>" +
"<ATTRIBUTE name=\"Description\" type=\"STRING\">I WANT THIS PARA 2</ATTRIBUTE>" +
"</MODELATTRIBUTES>" +
"</MODEL>" +
"</MODELS>" +
"</ADOXML>";
public static void main(String[] args) {
DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = null;
try {
builder = builderFactory.newDocumentBuilder();
Document document = builder.parse(new ByteArrayInputStream(EXAMPLE_XML.getBytes()));
XPath xPath = XPathFactory.newInstance().newXPath();
String expression = "/ADOXML/MODELS/MODEL/MODELATTRIBUTES/ATTRIBUTE[#name='Description'][#type='STRING']";
NodeList nodeList = (NodeList) xPath.compile(expression).evaluate(document, XPathConstants.NODESET);
for (int i = 0; i < nodeList.getLength(); i++) {
System.out.println("###" + nodeList.item(i).getFirstChild().getNodeValue() + "###");
}
} catch (Exception e) {
System.out.print(e);
}
}
OUTPUT:
###I WANT THIS PARA 2###
The mentioned code works fine.
You can try other way also to get the text node -
String expression = "/ADOXML/MODELS/MODEL/MODELATTRIBUTES/ATTRIBUTE/text()";
NodeList nodeList = (NodeList) xPath.compile(expression).evaluate(document, XPathConstants.NODESET);
System.out.println(nodeList.item(0).getNodeValue());
Node.getTextContent() returns the text content of the current node and its descendants.
is there a way to get text content of the current node, not the descendant's text.
Example
<paragraph>
<link>XML</link>
is a
<strong>browser based XML editor</strong>
editor allows users to edit XML data in an intuitive word processor.
</paragraph>
expected output
paragraph = is a editor allows users to edit XML data in an intuitive word processor.
link = XML
strong = browser based XML editor
i tried below code
String str = "<paragraph>"+
"<link>XML</link>"+
" is a "+
"<strong>browser based XML editor</strong>"+
"editor allows users to edit XML data in an intuitive word processor."+
"</paragraph>";
org.w3c.dom.Document domDoc = null;
DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder docBuilder;
try {
docBuilder = docFactory.newDocumentBuilder();
ByteArrayInputStream bis = new ByteArrayInputStream(str.getBytes());
domDoc = docBuilder.parse(bis);
} catch (ParserConfigurationException e1) {
e1.printStackTrace();
} catch (SAXException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
DocumentTraversal traversal = (DocumentTraversal) domDoc;
NodeIterator iterator = traversal.createNodeIterator(
domDoc.getDocumentElement(), NodeFilter.SHOW_ELEMENT, null, true);
for (Node n = iterator.nextNode(); n != null; n = iterator.nextNode()) {
String tagname = ((Element) n).getTagName();
System.out.println(tagname + "=" + ((Element)n).getTextContent());
}
but it gives the output like this
paragraph=XML is a browser based XML editoreditor allows users to edit XML data in an intuitive word processor.
link=XML
strong=browser based XML editor
note the paragraph element contains the text of link and strong tag, which i dont want.
please suggest some ideas?
What you want is to filter children of your node <paragraph> to only keep ones with node type Node.TEXT_NODE.
This is an example of method that will return you the desired content
public static String getFirstLevelTextContent(Node node) {
NodeList list = node.getChildNodes();
StringBuilder textContent = new StringBuilder();
for (int i = 0; i < list.getLength(); ++i) {
Node child = list.item(i);
if (child.getNodeType() == Node.TEXT_NODE)
textContent.append(child.getTextContent());
}
return textContent.toString();
}
Within your example it means:
String str = "<paragraph>" + //
"<link>XML</link>" + //
" is a " + //
"<strong>browser based XML editor</strong>" + //
"editor allows users to edit XML data in an intuitive word processor." + //
"</paragraph>";
Document domDoc = null;
try {
DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
ByteArrayInputStream bis = new ByteArrayInputStream(str.getBytes());
domDoc = docBuilder.parse(bis);
} catch (Exception e) {
e.printStackTrace();
}
DocumentTraversal traversal = (DocumentTraversal) domDoc;
NodeIterator iterator = traversal.createNodeIterator(domDoc.getDocumentElement(), NodeFilter.SHOW_ELEMENT, null, true);
for (Node n = iterator.nextNode(); n != null; n = iterator.nextNode()) {
String tagname = ((Element) n).getTagName();
System.out.println(tagname + "=" + getFirstLevelTextContent(n));
}
Output:
paragraph= is a editor allows users to edit XML data in an intuitive word processor.
link=XML
strong=browser based XML editor
What it does is iterating on all the children of a Node, keeping only TEXT (thus excluding comments, node and so on) and accumulating their respective text content.
There is no direct method in Node or Element to get only the text content at first level.
If you change the last for loop into the following one it behaves as you wanted
for (Node n = iterator.nextNode(); n != null; n = iterator.nextNode()) {
String tagname = ((Element) n).getTagName();
StringBuilder content = new StringBuilder();
NodeList children = n.getChildNodes();
for(int i=0; i<children.getLength(); i++) {
Node child = children.item(i);
if(child.getNodeName().equals("#text"))
content.append(child.getTextContent());
}
System.out.println(tagname + "=" + content);
}
I do this with Java 8 streams and a helper class:
import java.util.*;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
public class NodeLists
{
/** converts a NodeList to java.util.List of Node */
static List<Node> list(NodeList nodeList)
{
List<Node> list = new ArrayList<>();
for(int i=0;i<nodeList.getLength();i++) {list.add(nodeList.item(i));}
return list;
}
}
And then
NodeLists.list(node)
.stream()
.filter(node->node.getNodeType()==Node.TEXT_NODE)
.map(Node::getTextContent)
.reduce("",(s,t)->s+t);
Implicitly don't have any function for the actual node text but with a simple trick you can do it. Ask if the node.getTextContent() contains "\n", if that is the case then the actual node don't have any text.
Hope this help.
I'm trying to parse XML strings into a Document that I can use for easy searching. But when I run into certain kinds of XML, it doesn't seem to work. The document is never constructed, and is null when it encounters an XML message like I have at the bottom. An excpetion is not thrown by anything in my try/catch
My code currently looks like this:
Document convertMessageToDoc(String message){
Document doc = null;
try {
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
dbf.setNamespaceAware(true);
DocumentBuilder db = dbf.newDocumentBuilder();
InputSource is = new InputSource();
is.setCharacterStream(new StringReader(message));
doc = db.parse(is);
}
catch (Exception e) {
//e.printStackTrace();
doc = null;
}
return doc;
}
What are some ways that I would be able to work with something like this:
<ns1:SubmitFNOLResponse xmlns:ns1="http://website.com/">
<ns1:FNOLReporting xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:type="ns1:FNOLReporting">
<ns1:FNOLResponse>
<ns1:FNOLStatusInfo>
<ns1:StatusCode>0</ns1:StatusCode>
<ns1:StatusMessages />
</ns1:FNOLStatusInfo>
</ns1:FNOLResponse>
</ns1:FNOLReporting>
</ns1:SubmitFNOLResponse>
It looks like your document is not "well formed". You need a single root element where you have two sibling "ns1:Prod" tags at the root.
Your document is not well-formed XML. Once it is, everything appears to work as expected.
String message =
"<ns1:Prods xmlns:ns1='/foo'>"// xmlns:ns1='uri'>"
+ "<ns1:Prod>"
+ " <ns1:ProductID>316</ns1:ProductID>"
+ " <ns1:Name>Blade</ns1:Name>"
+ "</ns1:Prod>"
+ "<ns1:Prod>"
+ " <ns1:ProductID>317</ns1:ProductID>"
+ " <ns1:Name>LL Crankarm</ns1:Name>"
+ " <ns1:Color>Black</ns1:Color>"
+ "</ns1:Prod>"
+ "</ns1:Prods>";
Document doc = null;
try {
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
dbf.setNamespaceAware(true);
dbf.setValidating(false);
DocumentBuilder db = dbf.newDocumentBuilder();
InputSource is = new InputSource();
is.setCharacterStream(new StringReader(message));
doc = db.parse(is);
NodeList sections = doc.getElementsByTagName("ns1:Prod");
int numSections = sections.getLength();
for (int i = 0; i < numSections; i++) {
Element section = (Element) sections.item(i);
NodeList prodinfos = section.getChildNodes();
for (int j = 0; j < prodinfos.getLength(); j++) {
Node info = prodinfos.item(j);
if (info.getNodeType() != Node.TEXT_NODE) {
System.out.println(info.getNodeName() + ": " + info.getTextContent());
}
}
System.out.println("");
}
} catch (Exception e) {
e.printStackTrace();
doc = null;
}
// Outputs
ns1:ProductID: 316
ns1:Name: Blade
ns1:ProductID: 317
ns1:Name: LL Crankarm
ns1:Color: Black