Extract some part of an XML - java

I have an xml and I want to extract some part of that. But I am unable to get it.
If I used variables and put every key in variables I can get that part but it is a very lengthy process. So is there any short process for it?
Below is the XML :
<?xml version=\"1.0\" encoding=\"UTF-8\"?><xs:nml
xmlns:xs=\"http://www.netgear.com/protocol/transaction/NMLSchema-0.9\" src=\"nas\" dst=\"dpv_1461117132000\" locale=\"en-us\">
<xs:transaction ref-id=\"\" type=\"0\">
<xs:response ref-id=\"njl_id_1941\" status=\"success\">
<xs:result>
<xs:get-s resource-id=\"network_link_list\" resource-type=\"network_link_collection\">
<network_link_collection>
<network_link resource-id=\"eth0\">
<link>eth0</link>
<ifname>eth0</ifname>
<speed>1000</speed>
<path/>
<duplex>full</duplex>
<vlanid>0</vlanid>
<iptype>ipv4dhcp</iptype>
<ipv6type>ipv6dhcp</ipv6type>
<ip>0.0.0.0</ip>
<subnet>255.255.255.0</subnet>
<broadcast>0.0.0.0</broadcast>
<ipv6>::</ipv6>
<subnet6>::</subnet6>
<prefixlength>64</prefixlength>
<ipv6_link>::</ipv6_link>
<prefixlength_link>64</prefixlength_link>
<mac>6C:B0:CE:1C:CA:AE</mac>
<mtu>1500</mtu>
<router>0.0.0.0</router>
<router6>0.0.0.0</router6>
<state>down</state>
<dnscollection/>
<routecollection/>
<ntpcollection/>
</network_link>
</network_link_collection>
</xs:get-s>
</xs:result>
</xs:response>
</xs:transaction>
I want the xml which comes inside network link collection.

You can create a map of property key-value pairs fairly easily. You just need to find the nodes that you want to pull out.
NodeList nodeList = doc.getElementsByTagName("network_link").item(0).getChildNodes();
ParseResponseXML.java
import java.io.*;
import java.net.*;
import java.util.*;
import javax.xml.parsers.*;
import org.w3c.dom.*;
public class ParseResponseXML {
public static void main(String[] args) {
try {
File fXmlFile = getResourceAsFile("resources/Response.xml");
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
Document doc = dBuilder.parse(fXmlFile);
doc.getDocumentElement().normalize(); // http://stackoverflow.com/questions/13786607
NodeList nodeList = doc.getElementsByTagName("network_link").item(0).getChildNodes();
Map<String, String> propertyMap = nodeListToMap(nodeList);
for (Map.Entry<String, String> entry : propertyMap.entrySet()) {
System.out.printf("%-18s => %s%n", entry.getKey(), entry.getValue());
}
} catch (Exception e) {
e.printStackTrace();
}
}
private static Map<String, String> nodeListToMap(NodeList nodeList) {
Map<String, String> result = new LinkedHashMap<String, String>();
for (int temp = 0; temp < nodeList.getLength(); temp++) {
Node node = nodeList.item(temp);
if (node.getNodeType() == Node.ELEMENT_NODE) {
Element element = (Element) node;
result.put(element.getTagName(), element.getTextContent());
}
}
return result;
}
private static File getResourceAsFile(String resource) throws IOException {
ClassLoader loader = Parse.class.getClassLoader();
File resourceFile = null;
if (loader instanceof URLClassLoader) {
URLClassLoader urlClassLoader = URLClassLoader.class.cast(loader);
URL resourceUrl = urlClassLoader.findResource(resource);
if ("file".equals(resourceUrl.getProtocol())) {
try {
URI uri = resourceUrl.toURI();
resourceFile = new File(uri);
} catch (URISyntaxException e) {
IOException ioException = new IOException("Unable to get file through class loader: " + loader);
ioException.initCause(e);
throw ioException;
}
}
}
if (resourceFile == null) {
throw new IOException("Unable to get file through class loader: " + loader);
}
return resourceFile;
}
}
Response.xml
Make sure you have the </xs:nml> closing tag at the end of the XML.
<?xml version="1.0" encoding="UTF-8"?>
<xs:nml xmlns:xs="http://www.netgear.com/protocol/transaction/NMLSchema-0.9"
src="nas" dst="dpv_1461117132000" locale="en-us">
<xs:transaction ref-id="" type="0">
<xs:response ref-id="njl_id_1941" status="success">
<xs:result>
<xs:get-s resource-id="network_link_list" resource-type="network_link_collection">
<network_link_collection>
<network_link resource-id="eth0">
<link>eth0</link>
<ifname>eth0</ifname>
<speed>1000</speed>
<path />
<duplex>full</duplex>
<vlanid>0</vlanid>
<iptype>ipv4dhcp</iptype>
<ipv6type>ipv6dhcp</ipv6type>
<ip>0.0.0.0</ip>
<subnet>255.255.255.0</subnet>
<broadcast>0.0.0.0</broadcast>
<ipv6>::</ipv6>
<subnet6>::</subnet6>
<prefixlength>64</prefixlength>
<ipv6_link>::</ipv6_link>
<prefixlength_link>64</prefixlength_link>
<mac>6C:B0:CE:1C:CA:AE</mac>
<mtu>1500</mtu>
<router>0.0.0.0</router>
<router6>0.0.0.0</router6>
<state>down</state>
<dnscollection />
<routecollection />
<ntpcollection />
</network_link>
</network_link_collection>
</xs:get-s>
</xs:result>
</xs:response>
</xs:transaction>
</xs:nml>
Output
link => eth0
ifname => eth0
speed => 1000
path =>
duplex => full
vlanid => 0
iptype => ipv4dhcp
ipv6type => ipv6dhcp
ip => 0.0.0.0
subnet => 255.255.255.0
broadcast => 0.0.0.0
ipv6 => ::
subnet6 => ::
prefixlength => 64
ipv6_link => ::
prefixlength_link => 64
mac => 6C:B0:CE:1C:CA:AE
mtu => 1500
router => 0.0.0.0
router6 => 0.0.0.0
state => down
dnscollection =>
routecollection =>
ntpcollection =>
Unwrap XML
If you want to unwrap a node, you can perform the following.
import java.io.*;
import java.net.*;
import javax.xml.parsers.*;
import javax.xml.transform.*;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import org.w3c.dom.*;
import org.xml.sax.SAXException;
public class ParseResponseXML {
public static void main(String[] args) {
try {
Document inputDoc = load("resources/Response.xml");
Document outputDoc = unwrap(inputDoc, "network_link_collection");
write(outputDoc, "NetworkLinkCollection.xml");
} catch (Exception e) {
e.printStackTrace();
}
}
public static Document load(String resource) throws IOException, ParserConfigurationException, SAXException {
File file = getResourceAsFile(resource);
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
return dBuilder.parse(file);
}
public static void write(Document doc, String filename) throws TransformerException {
TransformerFactory transformerFactory = TransformerFactory.newInstance();
Transformer transformer = transformerFactory.newTransformer();
DOMSource source = new DOMSource(doc);
StreamResult result = new StreamResult(new File(filename));
// StreamResult result = new StreamResult(System.out); // Output to console.
transformer.transform(source, result);
}
public static Document unwrap(Document doc, String tagName) throws ParserConfigurationException {
Node node = doc.getElementsByTagName(tagName).item(0);
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
Document result = dBuilder.newDocument();
Node importNode = result.importNode(node, true);
result.appendChild(importNode);
return result;
}
private static File getResourceAsFile(String resourceName) throws IOException {
ClassLoader loader = ParseResponseXML.class.getClassLoader();
File resourceFile = null;
if (loader instanceof URLClassLoader) {
URLClassLoader urlClassLoader = URLClassLoader.class.cast(loader);
URL resourceUrl = urlClassLoader.findResource(resourceName);
if ("file".equals(resourceUrl.getProtocol())) {
try {
URI uri = resourceUrl.toURI();
resourceFile = new File(uri);
} catch (URISyntaxException e) {
IOException ioException = new IOException("Unable to get file through class loader: " + loader);
ioException.initCause(e);
throw ioException;
}
}
}
if (resourceFile == null) {
throw new IOException("Unable to get file through class loader: " + loader);
}
return resourceFile;
}
}
NetworkLinkCollection.xml
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<network_link_collection>
<network_link resource-id="eth0">
<link>eth0</link>
<ifname>eth0</ifname>
<speed>1000</speed>
<path />
<duplex>full</duplex>
<vlanid>0</vlanid>
<iptype>ipv4dhcp</iptype>
<ipv6type>ipv6dhcp</ipv6type>
<ip>0.0.0.0</ip>
<subnet>255.255.255.0</subnet>
<broadcast>0.0.0.0</broadcast>
<ipv6>::</ipv6>
<subnet6>::</subnet6>
<prefixlength>64</prefixlength>
<ipv6_link>::</ipv6_link>
<prefixlength_link>64</prefixlength_link>
<mac>6C:B0:CE:1C:CA:AE</mac>
<mtu>1500</mtu>
<router>0.0.0.0</router>
<router6>0.0.0.0</router6>
<state>down</state>
<dnscollection />
<routecollection />
<ntpcollection />
</network_link>
</network_link_collection>

Great response from Mr. Polywhirl!! Thanks a lot!!
I only want to add that if what you want is to extract a part of the xml but without including xml header (), like me, you have to add this in the "write" method:
transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");

Related

Reading a value from XMLnode

I am very new to XML parsing. I am trying to read the XML file from a shared drive on my computer and moving them to another shared drive. I have the below XML file. i am trying to read the Test.pdf value from this XML document
<?xml version="1.0" encoding="utf-8" ?>
<xml>
<IndexData FileName="Test.pdf">
<AttachmentID>3221929</AttachmentID>
<URI>test234555..pdf</URI>
<postmarkDate>2018-07-02T12:52:00.9</postmarkDate>
<pin>305270036</pin>
<scanDate>2018-07-02T12:52:00.9</scanDate>
<UserLogin>admin</UserLogin>
</IndexData>
<IndexData FileName="Test2.pdf">
<AttachmentID>3221931</AttachmentID>
<URI>Appp2.pdf</URI>
<postmarkDate>2018-07-02T14:19:22.5</postmarkDate>
<pin>305270036</pin>
<scanDate>2018-07-02T14:19:22.5</scanDate>
<UserLogin>admin</UserLogin>
</IndexData>
</xml>
I tried importing import org.w3c.dom.Node; for this. Below is my code:
String processXml(Node doc) {
String fileName = null;
try {
DfLogger.debug(this, "Loading: " + doc.getNodeName(), null, null);
Map<String, String> indexData = getXmlData(doc);
fileName = indexData.get("IndexData FileName");
if (new File(fileName).exists()) {
import(fileName, indexData);
}
} catch (Exception ex) {
DfLogger.error(this, "Error processing document.", null, ex);
return null;
}
return fileName;
}
My value for FileName is always NULL when I am trying to read the value by doing this:
fileName = indexData.get("IndexData FileName");
below is my getXmlData method.
protected Map<String, String> getXmlData(Node xmlDataNode) {
Map<String, String> xmlData = new HashMap<>();
NodeList nodeList = xmlDataNode.getChildNodes();
for (int i = 0; i < nodeList.getLength(); i++) {
Node node = nodeList.item(i);
if (node.getNodeType() == Node.ELEMENT_NODE) {
xmlData.put(node.getNodeName(), node.getTextContent().trim());
}
}
return xmlData;
}
The caller method for processXML is below:
Public void processIncomingfiles(String documentTagName) throws Exception {
DfLogger.debug(this, "Import Process Begin ---- exportPath=" + exportPath, null, null);
try {
File dir = new File(exportPath);
if (dir.isDirectory()) {
FilenameFilter xmlFiles = new FilenameFilter() {
public boolean accept(File dir, String name) {
return name.toLowerCase().endsWith(".xml");
}
};
for (File file : dir.listFiles(xmlFiles)) {
if (!file.isDirectory()) {
DfLogger.debug(this, "Loading XML file: " + file.getAbsolutePath(), null, null);
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder documentBuilder = dbFactory.newDocumentBuilder();
FileInputStream fileStream = new FileInputStream(file);
try {
// Use FileInputStream instead of File since parse will leave file locked on error
Document doc = documentBuilder.parse(fileStream);
fileStream.close();
fileStream = null;
doc.getDocumentElement().normalize();
NodeList nodeList = doc.getElementsByTagName(documentTagName);
List<Node> errors = new ArrayList<>();
for (int i = 0; i < nodeList.getLength(); i++) {
String documentFilename = processXml(nodeList.item(i));
if (documentFilename != null) {
moveFileToProcessedSuccessful(documentFilename);
} else {
DfLogger.debug(
this,
"Error processing document in file: " + file.getName(),
null,
null);
errors.add(nodeList.item(i));
}
}
if (!errors.isEmpty()) {
if (errors.size() == nodeList.getLength()) {
safeMove(file, file.getAbsolutePath() + ".errors");
} else {
Node parent = nodeList.item(0).getParentNode();
for (Node errorDoc : errors) {
parent.removeChild(errorDoc);
}
writeXml(doc, file.getAbsolutePath());
moveFileToProcessedSuccessful(file);
while (nodeList.getLength() > 0) {
parent.removeChild(nodeList.item(0));
}
for (Node errorDoc : errors) {
parent.appendChild(errorDoc);
}
writeXml(doc, file.getAbsolutePath() + ".errors");
}
} else {
moveFileToProcessedSuccessful(file);
}
} catch (Exception ex) {
DfLogger.error(this, "Error parsing XML File.", null, ex);
if (fileStream != null) {
fileStream.close(); // If DocBuilder.parse fails, leaves file locked
}
safeMove(file, file.getAbsolutePath() + ".error");
}
}
}
}
} catch (Exception ex) {
DfLogger.error(this, "Error in XML Parser.", null, ex);
throw ex;
}
DfLogger.debug(this, "Import Process Ends -----------", null, null);
}
/**
* Process the Xml for the give document node.
* #param doc xml node
* #return filename of successfully processed document, otherwise null
*/
any help will be appreciated.
Lets assume you have your xml data in test.xml file. You can read file and get specific data from your xml using the below code:
package yourPackage;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.xml.sax.SAXException;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
public class Main {
public static void main(String[] args) throws IOException, ParserConfigurationException, SAXException {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setNamespaceAware(true);
Document doc = factory.newDocumentBuilder().parse(Files.newInputStream(Paths.get("test.xml")));
doc.getDocumentElement().normalize();
Element data = (Element)doc.getElementsByTagName("IndexData").item(0);
System.out.println(data.getAttribute("FileName"));
}
}
The output is :
Test.pdf

Trying to bring the properties/values such as the names or dates of an XML file into java from a directory

Trying to bring the properties/values such as the names or dates of an XML file into java from a directory. but the problem is i can only bring in the names of the files such as Employee or Dates but cannot bring in the elements inside the file
public class ProcessXML {
public static void main2(String[] args) {
File f = null;
File[] paths;
try{
// file
f = new File("/Users/Adrian/Dropbox/XML.xml");
// array of files and directory
paths = f.listFiles();
// for each name in the path array
for(File path:paths)
{
path.isDirectory();
// prints filename and directory name
System.out.println(path);
}
}catch(Exception e){
// if any error occurs
e.printStackTrace();
}
}
public static void main(String[] args) {
File f = null;
try{
// file
f = new File("Users/Adrian/Dropbox/XML.xml");
//other file
//f = new File("/Users/Adrian/Dropbox/");
listFile(f, " ");
}catch(Exception e){
// if any error occurs
e.printStackTrace();
}
}
private static void listFile(final File file, final String indent) throws IOException, ParserConfigurationException, SAXException {
if (file.isFile()) {
if (file.getName().endsWith(".xml")) {
System.out.println(indent + "File " + file.getName());
// final InputStream is = new FileInputStream(file);
processXML(file);
}
} else if (file.isDirectory()) {
System.out.println(indent + "Dir " + file.getName());
final File[] children = file.listFiles();
for (final File child : children) {
listFile(child, indent + " ");
}
}
}
private static void processXML(final File file) throws
IOException, ParserConfigurationException, SAXException {
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Document doc = db.parse(file);
}
}
Trying to bring the properties/values such as the names or dates of an XML file into java from a directory.the problem i am now having is trying to get the xml values out of the xml files i am nout sure what way to about it so if anyone has examples or can tell me which way to go about it it would be very appreciated
My guess is that it can not find the file since you didn't include the extension to the xml file.
try add .xml to the end of the file path and see if that works
import java.io.File;
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;
public class XPathTest {
public static void main(String args[]) {
try {
File Employee = new File("Employee.xml");
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
Document doc = dBuilder.parse(Employee);
doc.getDocumentElement().normalize();
System.out.println("root of xml file" + doc.getDocumentElement().getNodeName());
NodeList nodes = doc.getElementsByTagName("Employee");
System.out.println("==========================");
for (int i = 0; i < nodes.getLength(); i++) {
Node node = nodes.item(i);
if (node.getNodeType() == Node.ELEMENT_NODE) {
Element element = (Element) node;
System.out.println("Employee Age: " + getValue("age", element));
System.out.println("Employee Name: " + getValue("name", element));
System.out.println("Employee Gender: " + getValue("gender", element));
System.out.println("Employee Role: " + getValue("role", element));
}
}
} catch (Exception ex) {
ex.printStackTrace();
}
}
private static String getValue(String tag, Element element) {
NodeList nodes = element.getElementsByTagName(tag).item(0).getChildNodes();
Node node = (Node) nodes.item(0);
return node.getNodeValue();
}
}
went onto change everything and now it works, brought in xml values without a problem

XML Utility class exist for simple modification - add, remove/delete, change/modify?

Does a Java library exist that has the capability shown in the client code below? I'm looking for a library that provides basic XML manipulation capabilities using strings.
MagicXml mXml = MagicXmlUtil.createXml("<team name='cougars'><players><player name='Michael'/></players></team>");
mXml.addNode("players", "<player name='Frank'/>");
mXml.addNode("players", "<player name='Delete Me'/>");
mXml.removeNode("player[#name='Delete Me']");
mXml.addAttribute("team[#name='cougars']", "city", "New York");
mXml.addAttribute("team[#name='cougars']", "deleteMeAttribute", "Delete Me");
mXml.removeAttribute("team[#name='cougars']", "deleteMeAttribute");
mXml.modifyAttribute("player[#name='Michael']", "name", "Mike");
mXml.setNodeValue("player[#name='Mike']", "node value for Mike");
MagicXmlNode node = mXml.getNode("<player[#name='Frank'/>");
mXml.addNode("players", node);
mXml.modifyAttribute("player[#name='Frank'][1]", "name", "Frank2");
System.out.println("mXml:\n" + mXml.toString());
mXml:
<team name='cougars' city="New York">
<players>
<player name='Mike'>
node value for Mike
</player>
<player name='Frank' />
<player name='Frank2' />
</players>
</team>
there are many different java libraries for xml manipulation/editing, the basics one with java standard library are hard to use if your a beginner so you should try JDOM(java document object model) for parsing and editing is easy.
Read a bit of documentation and download sample code here if you want to try http://www.jdom.org/ good luck =)
Whether you use something already existing like dom4j or jdom or as I said in my comment you create a simple class that wraps call to finding nodes using XPath and adding/removing what you want (Nodes, Attributes etc).
This is a sample class, I'll let you add what's missing (modifyAttribute, setNodeValue etc)
import java.io.*;
import javax.xml.parsers.*;
import javax.xml.transform.*;
import javax.xml.transform.dom.*;
import javax.xml.transform.stream.*;
import javax.xml.xpath.*;
import org.w3c.dom.*;
public class MagicXml {
static XPath xpath = XPathFactory.newInstance().newXPath();
Document doc;
Element root;
public MagicXml(String xml) throws Exception {
doc = parseXml(xml);
root = doc.getDocumentElement();
}
private static Document parseXml(String xml) throws Exception {
DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
ByteArrayInputStream bis = new ByteArrayInputStream(xml.getBytes());
return docBuilder.parse(bis);
}
private String asXPath(String path) {
return path.startsWith("/") ? path : "//" + path;
}
private static Node findNode(Document doc, String xPath) throws Exception {
XPathExpression expr = xpath.compile(xPath);
return (Node) expr.evaluate(doc, XPathConstants.NODE);
}
public static MagicXml createXml(String xml) throws Exception {
return new MagicXml(xml);
}
public MagicXml addNode(String path, String xml) throws Exception {
Document subDoc = parseXml(xml);
Node destNode = findNode(doc, asXPath(path));
Node srcNode = subDoc.getFirstChild();
destNode.appendChild(doc.adoptNode(srcNode.cloneNode(true)));
return this;
}
public MagicXml removeNode(String path) throws Exception {
Node destNode = findNode(doc, asXPath(path));
destNode.getParentNode().removeChild(destNode);
return this;
}
public MagicXml addAttribute(String path, String attr, String value) throws Exception {
Element destNode = (Element)findNode(doc, asXPath(path));
destNode.setAttribute(attr, value);
return this;
}
public MagicXml removeAttribute(String path, String attr) throws Exception {
Element destNode = (Element)findNode(doc, asXPath(path));
destNode.removeAttribute(attr);
return this;
}
public String docToString(Document doc) {
try {
Transformer transformer = TransformerFactory.newInstance().newTransformer();
transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");
StringWriter sw = new StringWriter();
transformer.transform(new DOMSource(doc), new StreamResult(sw));
return sw.toString();
} catch (Exception e) {
return "";
}
}
public String toString() {
return docToString(doc);
}
public static void main(String[] args) throws Exception {
System.out.println(//
MagicXml.createXml("<team name='cougars'><players><player name='Michael'/></players></team>")//
.addNode("players", "<player name='Frank'/>")//
.addNode("players", "<player name='Delete Me'/>")//
.removeNode("player[#name='Delete Me']") //
.addAttribute("player[#name='Frank']", "foo", "bar") //
.addAttribute("player[#name='Frank']", "bar", "bazz") //
.removeAttribute("player[#name='Frank']", "bar") //
.toString());
}
}
XStream is a very easy XML manipulation tool. It can go from java classes to XML and vice versa very easily.

How to append xml file in java

I've been using xml files to save data from my java program. I'm using the java DOM api. I want to add to the document by adding an element and then adding children to that element.
I tried doing it using this code but when i run it it does nothing. Is there another way of doing it that would be simple and work better? is there a way i can get this code working?
File file = new File("C:/users/peter/desktop/newxml.xml");
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Document document = db.parse(file);
Element newB = document.createElement("B");
Element newC = document.createElement("c");
newC.setTextContent("11");
Element newD = document.createElement("d");
newD.setTextContent("21");
Element newE = document.createElement("e");
newE.setTextContent("31");
newB.appendChild(newC);
newB.appendChild(newD);
newB.appendChild(newE);
document.getDocumentElement().appendChild(newB);
This java code works to append new node to the xml file......it is based on DOM
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import java.io.FileOutputStream;
public class writexml1 {
public static void main (String args[])
{
File docFile = new File("..\\jquery\\WebContent\\demo\\testing.xml");
Document doc = null;
try
{
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
doc = db.parse(docFile);
}
catch (java.io.IOException e)
{
System.out.println("Can't find the file");
}
catch (Exception e)
{
System.out.print("Problem parsing the file.");
}
Element root = doc.getDocumentElement();
System.out.println("The root element is " + root.getNodeName() + ".\n");
NodeList children = root.getChildNodes();
System.out.print("There are "+children.getLength()+" child elements.\n");
System.out.print("They are: \n");
//Print the file
for (Node child = root.getFirstChild();child != null;child = child.getNextSibling())
{
if (child.getNodeType() == child.TEXT_NODE)
{
System.out.println("Text: "+child.getNodeValue());
}
else if (child.getNodeType() == child.ELEMENT_NODE)
{
System.out.println(child.getNodeName()+" = "+child.getFirstChild().getNodeValue());
}
}
//NodeList deleteElement = root.getElementsByTagName("staff");
//Node deleteNode= deleteElement.item(0);
//root.removeChild(deleteNode);
Element staffElement = doc.createElement("staff");
Node updateText = doc.createTextNode("");
staffElement.appendChild(updateText);
//
Element firstName = doc.createElement("firstname");
String str_firstName="added firstname";
Node firstNameNode = doc.createTextNode(str_firstName);
firstName.appendChild(firstNameNode);
staffElement.appendChild(firstName);
//
Element lastName = doc.createElement("lastname");
String str_lastName="added lastname";
Node lastNameNode = doc.createTextNode(str_lastName);
lastName.appendChild(lastNameNode);
staffElement.appendChild(lastName);
//
Element nickName = doc.createElement("nickname");
String str_nickName="added nickname";
Node nickNameNode = doc.createTextNode(str_nickName);
nickName.appendChild(nickNameNode);
staffElement.appendChild(nickName);
//
Element salary = doc.createElement("salary");
String str_salary="$10,000";
Node salaryNode = doc.createTextNode(str_salary);
salary.appendChild(salaryNode);
staffElement.appendChild(salary);
//
root.appendChild(staffElement);
//Node StaffNode=(Node)updateElement;
try{
String outputURL = "..\\jquery\\WebContent\\demo\\testing.xml";
DOMSource source = new DOMSource(doc);
StreamResult result = new StreamResult(new FileOutputStream(outputURL));
TransformerFactory transFactory = TransformerFactory.newInstance();
Transformer transformer = transFactory.newTransformer();
transformer.transform(source, result);
} catch (Exception e) {
e.printStackTrace();
}
}
}
you should check out the JAXB API. If I understand right, you're xml looks like this:
<B>
<C>11</C>
<D>21</D>
<E>31</E>
</B>
So code would be:
import javax.xml.bind.JAXBContext;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAccessType;
#XmlRootElement
#XmlAccessorType(XmlAccessType.FIELD)
public class B {
#XmlElement public String C; // sloppy, probably should be type Integer or something
#XmlElement public String D;
#XmlElement public String E;
}
// then, somewhere else in your code you want to serialize...
B b = new B();
b.C = "11";
b.D = "21";
b.E = "31";
JAXBContext c = JAXBContext.newInstance(B.class);
// where w is a Writer instance
c.createMarshaller().marshal(b, w);

How can I append an attribute to an existing XML element in Java?

I want to append an attribute an existing element in XML using Java. For example:
<employee>
<details name="Jai" age="25"/>
<details name="kishore" age="30"/>
</employee>
It want to add weight to it (assume that it is calculated and then appended in response). How can I append that to all items?
<details name="Jai" age="25" weight="55"/>
import org.w3c.dom.*;
import java.io.*;
import javax.xml.parsers.*;
import javax.xml.transform.*;
import javax.xml.transform.dom.*;
import javax.xml.transform.stream.*;
public class AddAndPrint {
public static void main(String[] args) {
DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
Document doc = docBuilder.parse("/path/to/file.xml");
NodeList employees = document.getElementsByTagName("employee");
for (Node employee : employees) {
for (Node child : employee.getChildNodes() {
if ("details".equals(child.getNodeName()) child.setAttribute("weight", "150");
}
}
try {
Source source = new DOMSource(doc);
StringWriter stringWriter = new StringWriter();
Result result = new StreamResult(stringWriter);
TransformerFactory factory = TransformerFactory.newInstance();
Transformer transformer = factory.newTransformer();
transformer.transform(source, result);
System.out.println(stringWriter.getBuffer().toString());
} catch (TransformerConfigurationException e) {
e.printStackTrace();
} catch (TransformerException e) {
e.printStackTrace();
}
}
}
Here is a quick solution based on jdom:
public static void main(String[] args) throws JDOMException, IOException {
File xmlFile = new File("employee.xml");
SAXBuilder builder = new SAXBuilder();
Document build = builder.build(xmlFile);
XPath details = XPath.newInstance("//details");
List<Element> detailsNodes = details.selectNodes(build);
for (Element detailsNode:detailsNodes) {
detailsNode.setAttribute("weight", "70"); // static weight for demonstration
}
XMLOutputter outputter = new XMLOutputter(Format.getPrettyFormat());
outputter.output(build, System.out);
}
First, we build a document (SAXBuilder), next we create a XPath expression for the details node, then we iterate through the elements for that expression and add the weight attribute.
The last two lines just verify that it's white magic :-)

Categories

Resources