I did some codes but they are not working. I also need to validate if a header:message exists
String xml = "<header:HostError>
<header:message>
<header:messageCode>321</header:messageCode>
<header:message>test</header:message>
</header:message>
<header:message>
<header:messageCode>123</header:messageCode>
<header:message>test</header:message>
</header:message>
</header:HostError>"
How do I get the first messageCode and message?
private void extractErrorsFromResponse(SOAPFaultDetail faultResponse) {
for (Iterator itr = faultResponse.getAllDetailEntries(); itr.hasNext(); ) {
Object element = itr.next();
if (element instanceof OMElement) {
Object code = ((OMElement) element).getFirstChildWithName(new QName("message")).getFirstChildWithName(new QName("messageCode"));
Object message = ((OMElement) element).getFirstChildWithName(new QName("message")).getFirstChildWithName(new QName("message"));
faultResponse.addDetailEntry(((OMElement) element).cloneOMElement());
}
}
}
A quick solution would be that.
String xml = "<header:HostError>" +
"<header:message>\n" +
"<header:messageCode>321</header:messageCode>\n" +
"<header:message>test</header:message>\n" +
"</header:message>\n" +
"<header:message>\n" +
"<header:messageCode>123</header:messageCode>\n" +
"<header:message>test</header:message>\n" +
"</header:message>\n" +
"</header:HostError>";
DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
Document doc = docBuilder.parse(new InputSource(new StringReader(xml)));
NodeList list = doc.getElementsByTagName("header:messageCode");
System.out.println("First messageCode : " + list.item(0).getFirstChild().getNodeValue());
NodeList list_ = doc.getElementsByTagName("header:message");
System.out.println("First message : " + list_.item(1).getFirstChild().getNodeValue());
It prints,
First messageCode : 321
First message : test
Based on that, you need to find a more generic method.
Related
This question already has answers here:
Getting document as null [#document: null] After parsing XML in java using DocumentBuilder
(2 answers)
Closed 3 years ago.
I want to convert XML string into Document in java. the code is below..
package org.com;
import java.io.StringReader;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;
import org.xml.sax.InputSource;
public class MainPage {
public static void main(String[] args)
{
final String xmlStr = "<employees>" +
" <employee id=\"101\">" +
" <name>Lokesh Gupta</name>" +
" <title>Author</title>" +
" </employee>" +
" <employee id=\"102\">" +
" <name>Brian Lara</name>" +
" <title>Cricketer</title>" +
" </employee>" +
"</employees>";
//Use method to convert XML string content to XML Document object
Document doc = convertStringToXMLDocument( xmlStr);
doc.getDocumentElement().normalize();
//Verify XML document is build correctly
System.out.println(doc.getFirstChild().getNodeName());
}
private static Document convertStringToXMLDocument(String xmlString)
{
//Parser that produces DOM object trees from XML content
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
//API to obtain DOM Document instance
DocumentBuilder builder;
try
{
//Create DocumentBuilder with default configuration
builder = factory.newDocumentBuilder();
//Parse the content to Document object
Document doc = builder.parse(new InputSource(new StringReader(xmlString)));
return doc;
}
catch (Exception e)
{
e.printStackTrace();
}
return null;
}
}
But when i am trying to debug this code then Document is showing null like this.. [#document: null].
Here question is that how to convert XML string into only in Document object without using Nodelist to read child node one by one.
I referred this Example
Please help..
Thanks in advance
1,my example use jdom
2,like this code
final String xmlStr = "<employees>" +
" <employee id=\"101\">" +
" <name>Lokesh Gupta</name>" +
" <title>Author</title>" +
" </employee>" +
" <employee id=\"102\">" +
" <name>Brian Lara</name>" +
" <title>Cricketer</title>" +
" </employee>" +
"</employees>";
StringReader stringReader = new StringReader(xmlStr);
SAXBuilder builder = new SAXBuilder();
Document build = builder.build(stringReader);
Element rootElement = build.getRootElement();
List employee = rootElement.getChildren();
for (int i = 0; i < employee.size(); i++) {
Element emp = (Element) employee.get(i);
String id = emp.getAttributeValue("id");
String name = emp.getChildText("name");
String title = emp.getChildText("title");
System.out.printf("id: %s,name: %s, title : %s", id, name, title);
System.out.println();
}
I am attempting to get the text from an xml node. The code seems to recognize the node. This code
String L = "Node Length: " + nList.getLength()+ " Text: " + nList.item(0).toString();
jTextArea1.setText(L);
returns: Node Length: 1 Text: [CompanyName: null]
So it seems like the code is finding the node but not getting the value. Here is the whole code block (this is my first time posting so I hope I formatted this right!). the FOR loop should grab the value but is throwing a NULL Pointer Exception:
private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
try{
//Get Document Builder
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
//Build Document
Document xdocument = builder.parse(new File("request.xml"));
xdocument.getDocumentElement().normalize();
NodeList nList = xdocument.getElementsByTagName("CompanyName");
//String L = "Node Length: " + nList.getLength()+ " Text: " + nList.item(0).toString();
//jTextArea1.setText(L);
for (int temp = 0; temp < nList.getLength(); temp++)
{
Node node = nList.item(0);
if (node.getNodeType() == Node.ELEMENT_NODE)
{
Element eElement = (Element) node;
String nodetxt= "Company : " + eElement.getElementsByTagName("CompanyName").item(0).getTextContent() ;
jTextArea1.setText(nodetxt) ;
}
}
} catch (Exception ex) {
java.util.logging.Logger.getLogger(TechKnowPOSGUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
}
and here is the XML file:
<?xml version="1.0" encoding="utf-8"?>
<RunReportQueryAction xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<CompanyName>Techknow</CompanyName>
<IntegrationLoginId>cwapitest</IntegrationLoginId>
<IntegrationPassword>cwtest123</IntegrationPassword>
<ReportName>Company</ReportName>
<!-- <Conditions></Conditions> -->
<!-- <Limit>10</Limit> -->
<!-- <Skip></Skip> -->
<!-- <OrderBy></OrderBy> -->
</RunReportQueryAction>
Any help is greatly appreciated.
On this line you get all the CompanyName elements:
NodeList nList = xdocument.getElementsByTagName("CompanyName");
Then you loop through them in your for loop and call this:
eElement.getElementsByTagName("CompanyName")
But that would imply that the CompanyName has nested CompanyName elements, which it does not. Therefore you should use this in your for loop, as the elements you are iterating are already the CompanyName elements:
String nodeTxt = "Company : " + eElement.getTextContent()
I'm looking for ways to read a generic xml file
Here is an example of a normal xml file
<?xml version="1.0"?>
<students>
<student>
<name>John</name>
<grade>B</grade>
<age>12</age>
</student>
<student>
<name>Mary</name>
<grade>A</grade>
<age>11</age>
</student>
<student>
<name>Simon</name>
<grade>A</grade>
<age>18</age>
</student>
</students>
and here is example of a typical xml parser that would read that code and print it out
public class XMLParser {
public void getAllUserNames(String fileName) {
try {
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
File file = new File(fileName);
if (file.exists()) {
Document doc = db.parse(file);
Element docEle = doc.getDocumentElement();
// Print root element of the document
System.out.println("Root element of the document: "
+ docEle.getNodeName());
NodeList studentList = docEle.getElementsByTagName("student");
// Print total student elements in document
System.out
.println("Total students: " + studentList.getLength());
if (studentList != null && studentList.getLength() > 0) {
for (int i = 0; i < studentList.getLength(); i++) {
Node node = studentList.item(i);
if (node.getNodeType() == Node.ELEMENT_NODE) {
System.out
.println("=====================");
Element e = (Element) node;
NodeList nodeList = e.getElementsByTagName("name");
System.out.println("Name: "
+ nodeList.item(0).getChildNodes().item(0)
.getNodeValue());
nodeList = e.getElementsByTagName("grade");
System.out.println("Grade: "
+ nodeList.item(0).getChildNodes().item(0)
.getNodeValue());
nodeList = e.getElementsByTagName("age");
System.out.println("Age: "
+ nodeList.item(0).getChildNodes().item(0)
.getNodeValue());
}
}
} else {
System.exit(1);
}
}
} catch (Exception e) {
System.out.println(e);
}
}
public static void main(String[] args) {
XMLParser parser = new XMLParser();
parser.getAllUserNames("c:\\test.xml");
}
}
This code needs lines like this
NodeList studentList = docEle.getElementsByTagName("student");
NodeList nodeList = e.getElementsByTagName("name");
In order to work correctly.
My questions comes from how would I make that generic. Is there any way where I could read that same XML file without having to get specific elements by tagNames and yet still print it out in a view able format.
In the above example you are using Dom parser. By using Jaxb Context unmarshaller you can convert the xml to java object, then you can achive your task.
You need to have a generic function to handle.
Generic function is as follows:
/* Prints the Node Value */
public void PrintNodeValue(Element element, String tagName, String msg)
{
NodeList nodeList = element.getElementsByTagName(tagName);
System.out.println(msg + nodeList.item(0).getChildNodes().item(0).getNodeValue());
}
Function is called as below:
PrintNodeValue(e, "name", "Name: ");
PrintNodeValue(e, "grade", "Grade: ");
HI I am new to Java and trying to read an XML file.
Here is my XML file :-
<?xml version="1.0" encoding="UTF-8"?>
<parameter>
<attribute>a</attribute>
Here is my code I am trying to read the key and value from the xml but I am stuck .Here is my code :-
public class TestDBMain {
public static void main(String[] args) throws Exception {
// TODO Auto-generated method stub
File file = new File("ACL.xml");
DocumentBuilderFactory dbfactory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = dbfactory.newDocumentBuilder();
Document doc = builder.parse(file);
NodeList nList = doc.getElementsByTagName("testCaseDataName");
for(int i = 0;i<nList.getLength();i++){
Node nNode = nList.item(i);
if(nNode.getNodeType()== Node.ELEMENT_NODE){
Element ele = (Element) nNode;
// System.out.println(ele.getTextContent());
//System.out.println(ele.getElementsByTagName("testCaseName").item(0).getTextContent());
System.out.println(ele.getAttributeNode("testCaseDataName"));
//I dont know which methods to use to print the key and value in the xml under parameter
}
}
}
}
Can anyone please help me with this
Disclaimer: I maintain the JDOM project, so I am biased.... but... this is an ideal use case for JDOM:
Document doc = new SAXBuilder().build(new File("ACL.xml"));
Element root = doc.getRootElement();
for (Element testcase : root.getChildren()) {
int id = Integer.parseInt(testcase.getChildText("id"));
String name = testcase.getChildText("testCaseName");
String expect = testcase.getChildText("expectedResult");
Map<String,String> params = new LinkedHashMap<String,String>();
Element parmemt = testcase.getChild("parameter");
if (parmemt != null) {
Iterator<Element> it = parmemt.getChildren().iterator();
while (it.hasNext()) {
Element key = it.next();
if (!"key".equals(key.getName())) {
throw new IllegalStateException("Expected key but got " + key);
}
if (!it.hasNext()) {
throw new IllegalStateException("Expected value for key " + key);
}
Element val = it.next();
if (!"value".equals(val.getName())) {
throw new IllegalStateException("Expected value but got " + val);
}
params.put(key.getValue(), val.getValue());
}
}
System.out.printf("Processing test case %d -> %s\n Expect %s\n Parameters: %s\n",
id, name, expect, params.toString());
}
For me this produces the output
Processing test case 1 -> EditTest
Expect nooptionsacltrue
Parameters: {}
Processing test case 2 -> AddTest
Expect featuresaddedacltrue
Parameters: {featues=w,f}
Processing test case 3 -> AddTest
Expect duplicateacltrue
Parameters: {projectType=NEW, Name=28HPM, status=ACTIVE, canOrder=Yes}
your code read <testCaseDataName> node. it is not go inside of this tag.
so try this..
for(int i = 0;i<nList.getLength();i++){
NodeList nodeList = nList.item(i).getChildNodes();
for(int j = 0;j<nList.getLength();j++){
Node nNode = nodeList.item(j);
if(nNode.getNodeType()== Node.ELEMENT_NODE){
System.out.println(nNode.getNodeName() +" : "+nNode.getTextContent());
if(nNode.getNodeName().equals("parameter")){
NodeList param = nNode.getChildNodes();
System.out.println(" "+param.item(0).getNodeName() +" : "+param.item(0).getTextContent());
System.out.println(" "+param.item(1).getNodeName() +" : "+param.item(1).getTextContent());
}
}
}
}
I am trying to write DOM XML parsing.
My Xml file
<?xml version="1.0"?>
<BLAH>
<AgentNm type="citi1">
<accName>accName1</accName>
<accType>accType1</accType>
<someThing>someThing1</someThing>
<amt>100000</amt>
</AgentNm>
<AgentNm type="citi2">
<accName>accName2</accName>
<accType>accType2</accType>
<someThing>someThing2</someThing>
<amt>200000</amt>
</AgentNm>
</BLAH>
And i tried following java code
DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder();
Document doc = docBuilder.parse (new File("c:\\file.xml"));
// normalize text representation
doc.getDocumentElement ().normalize ();
System.out.println ("Root element of the doc is " +doc.getDocumentElement().getNodeName());
NodeList agentNm = doc.getElementsByTagName("AgentNm");
int totalAgentNm = agentNm.getLength();
System.out.println("Total no of Agents : " + totalAgentNm);
for(int s=0; s<agentNm.getLength() ; s++){
Node firstPersonNode = agentNm.item(s);
if(firstPersonNode.getNodeType() == Node.ELEMENT_NODE){
Element firstPersonElement = (Element)firstPersonNode;
PrintNodeElem(firstPersonElement,"type");
}//end of if clause
}//end of for loop with s var
static void PrintNodeElem(Element nodeElem,String elem){
NodeList someThingList = nodeElem.getElementsByTagName(elem);
Element ageElement = (Element)someThingList.item(0);
NodeList textAgeList = ageElement.getChildNodes();
System.out.println(elem+" : " +((Node)textAgeList.item(0)).getNodeValue().trim());
}
But, when i tried to execute above method,
i am getting null pointer exception.
can any one explain me, how to fix this.
if you want an attribute of a given node, I would suggest XPath. It is much easier.
http://onjava.com/onjava/2005/01/12/xpath.html