So I have an XML file that looks like the following:
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<!DOCTYPE config SYSTEM "config.dtd">
<config>
<domains>
</domains>
</config>
I need to create a new element called session with two attributes let's call this atrib 1 and atrib 2.
So ultimately I would like the XML file to look like this.
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<!DOCTYPE config SYSTEM "config.dtd">
<config>
<session atrib1="100" artib2="200" />
<domains>
</domains>
</config>
I've been playing around with the document builder but cannot seem to figure out how to get this to work.
Below is the modified version from the tips below. The new element is not being created and the & is being removed from the xml file.
File file = new File(fileLocaton);
DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
document = docBuilder().parse(file);
Element rootElement = document.getDocumentElement();
Element sSession = document.createElement("session");
// set attributes
sSession.setAttribute("attr1", "100");
sSession.setAttribute("attr2", "200");
// instead of appending, insert in front of the first child
rootElement.insertBefore(sSession, rootElement.getFirstChild());
DOMSource source = new DOMSource(document);
TransformerFactory transformerFactory = TransformerFactory.newInstance();
Transformer transformer = transformerFactory.newTransformer();
StreamResult result = new StreamResult(file.getPath());
transformer.transform(source, result);
Related
I have an XML like
<?xml version="1.0" encoding="UTF-8" standalone="no"?><root>
<parameters>
<param>
<name>john</name>
<age>18</age>
</param>
</parameters>
and would want to transform it like
<?xml version="1.0" encoding="UTF-8" standalone="no"?><root>
<parameters>
<L1>
<param>
<name>john</name>
<age>18</age>
</param>
</L1>
</parameters>
programmatically using DOM Java APIs to enclose the tags
If you want to do it programmatically, you can do this:
// load document
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document doc = builder.parse(url.toURI().toString());
// Transform document
Element root = doc.getDocumentElement();
Element elm = doc.createElement("L1");
while (root.hasChildNodes()) {
Node child = root.getFirstChild();
root.removeChild(child);
elm.appendChild(child);
}
root.appendChild(elm);
// Output to console for testing
TransformerFactory transformerFactory = TransformerFactory.newInstance();
Transformer transformer = transformerFactory.newTransformer();
DOMSource source = new DOMSource(doc);
StreamResult result = new StreamResult(System.out);
transformer.transform(source, result);
But you could rather use an XSLT stylesheet (you're using a transformer anyway).
Hi i am generating a xml file using javax.xml parsers able to generate a xml file. But in my attribute value i was getting " instead of double quote.
How to print double quotes in attribute value. Below is my code
Document doc = docBuilder.newDocument();
Element rootElement = doc.createElement("elements");
doc.appendChild(rootElement);
rootElement.setAttribute("area", "area");
rootElement.setAttribute("page", "pagename");
//element
Element element = doc.createElement("element");
rootElement.appendChild(element);
element.setAttribute("key", "key");
element.setAttribute("id", "id");
element.setAttribute("path", "//*[#id="email"]");
}
// write the content into xml file
TransformerFactory transformerFactory = TransformerFactory.newInstance();
Transformer transformer = transformerFactory.newTransformer();
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");
DOMSource source = new DOMSource(doc);
StreamResult result = new StreamResult(new File(ApplicationContext.getPath()+File.separator+"test.xml"));
// Output to console for testing
// StreamResult result = new StreamResult(System.out);
transformer.transform(source, result);
Output :
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<elements area="area" page="pagename">
<element id="id" key="key" path="//*[#id="email"]"/>
</elements>
Expected output:
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<elements area="area" page="pagename">
<element id="id" key="key" path="//*[#id="email"]"/>
</elements>
Thanks inadvance
The output you are trying to produce is not well-formed XML, and no XML parser will accept it. If you want to produce stuff that isn't XML then you can do so, of course, but XML-aware tools will try very hard to prevent it.
I need to set prefix of the element in my xml. I need to print the xml in the format below:
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<cars xmlns:dcterms="http://purl.org/dc/terms/" xmlns:msxsl="urn:schemas-microsoft-com:xslt">
<supercars company="Ferrari">
<dcterms:carname type="formula one">Ferrari 101</dcterms:carname>
<msxsl:carname type="sports">Ferrari 202</msxsl:carname>
</supercars>
</cars>
However, I am not able to add the prefix in my XML. What I am getting is this.
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<cars xmlns:dcterms="http://purl.org/dc/terms/" xmlns:msxsl="urn:schemas-microsoft-com:xslt">
<supercars company="Ferrari">
<carname type="formula one">Ferrari 101</carname>
<carname type="sports">Ferrari 202</carname>
</supercars>
</cars>
Following is my Java Code:
public static void main(String args[]) {
try {
DocumentBuilderFactory dbFactory =
DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder =
dbFactory.newDocumentBuilder();
Document doc = dBuilder.newDocument();
// root element
Element rootElement = doc.createElement("cars");
rootElement.setAttributeNS("http://www.w3.org/2000/xmlns/", "xmlns:dcterms", "http://purl.org/dc/terms/");
rootElement.setAttributeNS("http://www.w3.org/2000/xmlns/", "xmlns:msxsl", "urn:schemas-microsoft-com:xslt");
doc.appendChild(rootElement);
// supercars element
Element supercar = doc.createElement("supercars");
rootElement.appendChild(supercar);
// setting attribute to element
Attr attr = doc.createAttribute("company");
attr.setValue("Ferrari");
// supercar.setAttributeNodeNS(attr);
supercar.setAttributeNode(attr);
// carname element
Element carname = doc.createElement("carname");
Attr attrType = doc.createAttribute("type");
attrType.setValue("formula one");
carname.setAttributeNode(attrType);
carname.appendChild(
doc.createTextNode("Ferrari 101"));
supercar.appendChild(carname);
Element carname1 = doc.createElement("carname");
Attr attrType1 = doc.createAttribute("type");
attrType1.setValue("sports");
carname1.setAttributeNode(attrType1);
carname1.appendChild(
doc.createTextNode("Ferrari 202"));
supercar.appendChild(carname1);
// write the content into xml file
TransformerFactory transformerFactory =
TransformerFactory.newInstance();
Transformer transformer =
transformerFactory.newTransformer();
transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");
DOMSource source = new DOMSource(doc);
StreamResult result =
new StreamResult(new File("cars.xml"));
transformer.transform(source, result);
// Output to console for testing
StreamResult consoleResult =
new StreamResult(System.out);
transformer.transform(source, consoleResult);
} catch (Exception e) {
e.printStackTrace();
}
}
}
And I checked this link Adding namespace prefix XML String using XML DOM. However, this only talks about the SAX way of doing thing. I need to do this in DOM.
I tried setPrefix method and it is throwing me NAMESPACE_ERR
First of all, make sure you set dbFactory.setNamespaceAware(true);, if you want to work with a DOM supporting namespaces.
Then use createElementNS, e.g. Element carname = doc.createElementNS("http://purl.org/dc/terms/", "dcterms:carname");, to create elements in a namespace. Use the same approach for the element in the other namespace.
I wrote code below to get XML output.
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Document document = db.newDocument();
Element element = document.createElement("Test");
Text text = document.createTextNode("");
element.appendChild(text);
document.appendChild(element);
TransformerFactory transFactory = TransformerFactory.newInstance();
Transformer transformer = transFactory.newTransformer();
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
DOMSource source = new DOMSource(document);
StreamResult result = new StreamResult(System.out);
transformer.transform(source, result);
What I got is
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<Test/>
What I want to get is
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<Test></Test>
How can I do this?
Many thanks.
There is no clean way to do this..
If you feel comfortable to use duct-tape solutions, you could let your transformer output html instead of xml:
transformer.setOutputProperty(javax.xml.transform.OutputKeys.METHOD, "html");
But again, I have to point out that this is not a clean solution, but it did the trick for me as I was stuck with a similar problem
I have the following XML, I would like to add another "product" to the xml.
<?xml version="1.0" encoding="ISO-8859-1"?>
<products>
<product>
<name>Computer</name>
<code>PC1003</code>
<description>Basic Computer</description>
<price>399.99</price>
</product>
<product>
<name>Monitor</name>
<code>MN1003</code>
<description>LCD Monitor</description>
<price>99.99</price>
</product>
<product>
<name>Printer</name>
<code>PR1003x</code>
<description>Inkjet Printer</description>
<price>54.23</price>
</product>
</products>
This is the code I have so far:
// Variables
File file = new File("db_products.xml"); // set xml to parse
// Create builders
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
Document doc = dBuilder.parse(file); // load xml file
doc.getDocumentElement().normalize();
doc.createElement("product");
I don't really care where the new "product" section is added. I just can't seem to grasp what is the difference between a node and an element. I'm assuming the correct way to add a new "product" section would be to add a child to "products" and then add children (name,code,etc.) to "product".
Any help on how to easily do this, or a link to a simple tutorial would be appreciated.
What you need to do is retrieve the products element first and then call the appendChild on that element. Something like this:
Element productElement = doc.createElement("product");
productElement.setAttribute("name", "value");
//Other name value pairs...
//Append the products element to the right spot.
Element productsElement = (Element) doc.getElementByTagName("products").item(0);
productsElement.appendChild(productElement);
//Convert doc to xml string
DOMSource domSource = new DOMSource(doc);
StringWriter writer = new StringWriter();
StreamResult result = new StreamResult(writer);
TransformerFactory tf = TransformerFactory.newInstance();
Transformer transformer = tf.newTransformer();
transformer.transform(domSource, result);
String xmlAsString = writer.toString();