This is my demo.jsp page
String filename = "TestNode.xml";
ServletContext app = getServletContext();
String projectPath = app.getRealPath("/");
String result = projectPath + filename;
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
dbf.setValidating(false);
DocumentBuilder db = dbf.newDocumentBuilder();
Document doc = db.parse(new FileInputStream(new File(result)));
Element rootElement = doc.getDocumentElement();
Element element1 = doc.getDocumentElement();
Element element2 = doc.createElement("hai");
rootElement.appendChild(element2);
Element name = doc.createElement("welcome");
element2.appendChild(name);
element1.appendChild(element2);
DOMSource src = new DOMSource(doc);
TransformerFactory transformerFactory = TransformerFactory.newInstance();
Transformer transformer = null;
transformer = transformerFactory.newTransformer();
StreamResult rslt = new StreamResult(result);
transformer.transform(src, rslt);
for this i'm getting output as:
<root>
<hai>
<welcome/>
</hai>
</root>
but expected output is:
<root>
<hai>
<welcome>
</welcome>
</hai>
</root>
Where should I change the code to get expected result?
To obtain the output:
<root>
<hai>
<welcome>
</welcome>
</hai>
</root>
Where the <welcome> </welcome> element is actually not empty but contains at least one whitespace character, you need to create a text node and add it as the child of the welcome element:
Element name = doc.createElement("welcome");
Node textNode = doc.createTextNode(" ");
name.appendChild(textNode);
element2.appendChild(name);
Related
I want to extract code and text separately from the soap fault listed below. The code that I am using (listed below xml) is printing code and text together.
<env:Fault xmlns:env = "http://schemas.xmlsoap.org/soap/envelope/" xmlns:fault = "http://schemas.xmlsoap.org/soap/envelope/">
<faultcode>fault:Client</faultcode>
<faultstring>An error occurred. Please check the detail section.</faultstring>
<detail>
<e:serviceFault xmlns:e = "http://xml.comcast.com/types">
<e:messages>
<e:message>
<e:code>ERRORCODE-82828</e:code>
<e:text>Error Message.</e:text>
</e:message>
</e:messages>
</e:serviceFault>
</detail>
</env:Fault>
Code
public void printSoapFaultClientException(SoapFaultClientException e) {
TransformerFactory transformerFactory = TransformerFactory.newInstance();
Transformer transformer = null;
transformer = transformerFactory.newTransformer();
DOMResult result = new DOMResult();
transformer.transform(e.getSoapFault().getSource(), result);
NodeList nl = ((Document)result.getNode()).getElementsByTagName("detail");
System.out.println(" text content " + ((Element)nl.item(0)).getTextContent());
}
Here is an example of doing it , since it is a fault XML , i have just used a parser to parse the XML and extract a field off it. Also SOAPFaultClientException API's can help you extract the fault reason directly if you want it (http://docs.spring.io/spring-ws/site/apidocs/org/springframework/ws/soap/client/SoapFaultClientException.html)
File fXmlFile = new File("C:\\DevelopmentTools\\3.CODE\\SOAP.txt");
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
Document doc = dBuilder.parse(fXmlFile);
doc.getDocumentElement().normalize();
XPath xpath = XPathFactory.newInstance().newXPath();
String responseStatus = xpath.evaluate("//*[local-name()='code']/text()", doc);
String responseText = xpath.evaluate("//*[local-name()='text']/text()", doc);
System.out.println("---> " + responseStatus);
System.out.println("---> " + responseText);
I have a trouble in finding info about creating a multi level tags in xml file
for example i want next structure
<UserCards>
<UserCard userCardId="171">
<userName>somename</userName>
<userSurname>somesurname</userSurname>
<userAge>24</userAge>
<userAdress>someadress</userAdress>
<userPhone>223334455</userPhone>
<CurrentBooks>
<booName>someBookName</bookName>
</CurrentBooks>
</UserCard>
</UserCards>
I can create simple one level xml but how can I add new one?
DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder docBulder = docFactory.newDocumentBuilder();
//root mainElement
Document doc = docBulder.newDocument();
Element rootElement = doc.createElement("UserCards");
doc.appendChild(rootElement);
//root Book
Element UserCard = doc.createElement("UserCard");
rootElement.appendChild(UserCard);
...
...
//write in a XMLFile
TransformerFactory transformerFactory = TransformerFactory.newInstance();
Transformer transformer = transformerFactory.newTransformer();
DOMSource source = new DOMSource(doc);
StreamResult result = new StreamResult(new File("Test/UserCards.xml"));
seems to me like you answered it yourself....
You can append elements to any element, not just the root.
You create all Elements by calling doc.createElement("name")
and append to the parent element of your choice:
Elmenet userName = doc.createElement("userName");
Text userNameText = doc.createTextNode("somename");
userName.appendChild(userNameText);
UserCard.appendChild(userName);
Try this
Element rootElement = doc.createElement("UserCards");
doc.appendChild(rootElement);
//root Book
Element UserCard = doc.createElement("UserCard");
UserCard.setAttribute("userCardId" , "171");
Element userSurname = doc.createElement("userSurname");
UserCard.appendChild(userSurname);
Element userAge = doc.createElement("userAge");
UserCard.appendChild(userAge);
Element userAdress = doc.createElement("userAdress");
UserCard.appendChild(userAdress);
Element userPhone = doc.createElement("userPhone");
UserCard.appendChild(userPhone);
Element CurrentBooks = doc.createElement("CurrentBooks");
Element booKName = doc.createElement("booKName");
CurrentBooks.appendChild(booKName);
UserCard.appendChild(CurrentBooks);
rootElement.appendChild(UserCard);
I am linking to a webservice all works fine. Below is my codes.
private static void printSOAPResponse(SOAPMessage soapResponse) throws Exception {
TransformerFactory transformerFactory = TransformerFactory.newInstance();
Transformer transformer = transformerFactory.newTransformer();
Source sourceContent = soapResponse.getSOAPPart().getContent();
System.out.print("\nResponse SOAP Message = \n");
StreamResult result = new StreamResult(System.out);
transformer.transform(sourceContent, result);
}
I am not too sure of the transformerfactory. What I need to do now is to traverse through the results and look for below tag.
<Table diffgr:id="Table1" > and there after there will be few tags in it for e.g.
<rID>1212</rID>
<sNo>15677</sNo>
So what is the best way as some require to covert it into string is that necessary?
Transform to document (unchecked):
TransformerFactory tf = TransformerFactory.newInstance();
Transformer transformer = tf.newTransformer();
DOMResult result = new DOMResult();
transformer.transform(sourceContent, result);
Document doc = (Document) result.getNode();
Find in document:
String tag = "Table";
String attr = "diffgr:id";
String attrValue = "Table1";
NodeList list = doc.getElementsByTagName("Table");
Element tableNode = null;
for (int i = 0; i < list.getLength(); i++) {
tableNode = ((Element) list.item(i));
String currentAttrValue = tableNode.getAttribute(attr);
if (attrValue.equals(currentAttrValue)) {
break;
}
}
String childTag1 = "rID";
String childTag2 = "sNo";
Node child1 = (Node) tableNode.getElementsByTagName(childTag1).item(0);
Node child2 = (Node) tableNode.getElementsByTagName(childTag2).item(0);
String rIDValue = child1.getTextContent();
String sNoValue = child1.getTextContent();
You code Transformer transformer = transformerFactory.newTransformer(); is creating an "identity transformer" which copies the input unchanged, so it's not really doing anything useful. What you want here is a real (XSLT) transformer which actually extracts the information you need: something like
<xsl:template match="/">
<xsl:copy-of select="//Table[#diffgr:id='Table1']"/>
</xsl:template>
which you can compile using transformerFactory.newTemplates().
I have an XML document which has null values in its Value tag (something similar to below)
<ns2:Attribute Name="Store" NameFormat="urn:oasis:names:tc:SAML:2.0:attrname-format:uri">
<ns2:AttributeValue/>
</ns2:Attribute>
Now, I have to write Java code to modify the values as below.
<ns2:Attribute Name="Store" NameFormat="urn:oasis:names:tc:SAML:2.0:attrname-format:uri">
<ns2:AttributeValue>ABCDEF</ns2:AttributeValue>
</ns2:Attribute>
I am using DOM parser to parse the XML. I am able to delete the null tag for " but not able to add new values. I am not even sure if we have a direct way to replace or add the values.
Below is the code I am using to remove the child("")
Node aNode = nodeList.item(i);
eElement = (Element) aNode;
eElement.removeChild(eElement.getFirstChild().getNextSibling());
Thanks in advance
Just add data through setTextContent to the element. Sample code is as below:
public static void main(String[] args) throws IOException, SAXException, ParserConfigurationException, TransformerException {
String xml = "<ns2:Attribute Name=\"Store\" NameFormat=\"urn:oasis:names:tc:SAML:2.0:attrname-format:uri\"><ns2:AttributeValue/></ns2:Attribute>";
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
Document doc = dBuilder.parse(new ByteArrayInputStream(xml.getBytes()));
doc.getDocumentElement().normalize();
NodeList nList = doc.getElementsByTagName("ns2:AttributeValue");
for (int i=0;i<nList.getLength();i++) {
Element elem = (Element)nList.item(i);
elem.setTextContent("Content"+i);
}
TransformerFactory transformerFactory = TransformerFactory.newInstance();
Transformer transformer = transformerFactory.newTransformer();
DOMSource source = new DOMSource(doc);
StreamResult result = new StreamResult(System.out);
transformer.transform(source, result);
System.out.println(nList.getLength());
}
I've a xml document, which will be used as a template
<?xml version="1.0" encoding="UTF-8" standalone="no"?><entry xmlns="http://www.w3.org/2005/Atom" xmlns:d="http://schemas.microsoft.com/ado/2007/08/dataservices" xmlns:m="http://schemas.microsoft.com/ado/2007/08/dataservices/metadata"><content type="application/xml"><m:properties><d:AccountEnabled>true</d:AccountEnabled><d:DisplayName>SampleAppTestj5</d:DisplayName><d:MailNickname>saTestj5</d:MailNickname><d:Password>Qwerty1234</d:Password><d:UserPrincipalName>saTestj5#identropy.us</d:UserPrincipalName></m:properties></content></entry>
I'm calling it in java using this code where payLoadXML.xml has the above content.
"InputStream is = getClass().getClassLoader().getResourceAsStream("/payLoadXML.xml");"
Now I'm trying to edit the tag values for example changing the from "saTestj5" to "saTestj6" and then converting this entire xml and storing it in xml. Can anyone tell me how can I achieve this? I was told this can be done by using "Node" is it possible?
Use jaxb or sax parsers convert into object by using getter method and change the object and convert back to xml
try this
DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder docBuilder = null;
docBuilder = docFactory.newDocumentBuilder();
Document doc = null;
InputStream is = getClass().getClassLoader().getResourceAsStream("/payLoadXML.xml");
doc = docBuilder.parse(is);
Node staff = doc.getElementsByTagName("m:properties").item(0);
Text givenNameValue = doc.createTextNode("abc");
Element givenName = doc.createElement("d:GivenName");
givenName.appendChild(givenNameValue);
staff.appendChild(givenName);
TransformerFactory transformerFactory = TransformerFactory.newInstance();
Transformer transformer = null;
transformer = transformerFactory.newTransformer();
DOMSource source = new DOMSource(doc);
StringWriter writer = new StringWriter();
StreamResult result = new StreamResult(writer);
transformer.transform(source, result);