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.
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).
I am facing an issue while generating XML through Java code. I am printing the xml directly onto webpage to present the stats. The first line of the generated XML is always having some spaces at the start which makes the XML look weird. How do I remove the same. I tried removing the xml line but still whatever be the first line it has pre white spaces.
Please let me now how do i remove it
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<headNode>
<statsHead1>
<totalCount>0.05</totalCount>
</statsHead1>
<statsHead2>
<statsSubHead1>
<count1>0</count1>
<count2>0.0</count2>
</statsSubHead1>
<statsSubHead2>
<count1>0</count1>
<count2>0.0</count2>
</statsSubHead2>
<totalcount1>0</totalcount1>
<totalcount2>0.0</totalcount2>
</statsHead2>
</headNode>
Code that I use is
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);
StringWriter outWriter = new StringWriter();
Result result = new StreamResult(outWriter);
transformer.transform(source, result);
return outWriter.toString();
I have a legacy code with a lot of org.w3c.dom.Element generation like that
Document doc = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument();
Element exampleElement = doc.createElement("example");
exampleElement.appendChild(...
How can I convert exampleElement to XML string like that? (Any additional libraries is allowed)
<example>
...
</example>
Not that
<?xml version="1.0" encoding="UTF-8"?>
<example>
...
</example>
Transformer transformer = TransformerFactory.newInstance().newTransformer();
transformer.setOutputProperty(OMIT_XML_DECLARATION, "yes");
Writer writer = new StringWriter();
transformer.transform(new DOMSource(node), new StreamResult(writer));
return writer.toString();
There's some options:
Use an XSL Transformer to apply the changes using the directive omit-xml-declaration
Transformer transformer= TransformerFactory.newInstance().newTransformer();
transformer.setOutputProperty("omit-xml-declaration", "yes");
transformer.transform(new DOMSource(document), new StreamResult(stream));
Use a string replace process to replace the first line with a regex or using an indexOf("?>")
Depending on the implementation of w3c Document in the JDK used is possible to use some options in DOMConfiguration of the document like canonical-form
document.getDomConfig().setParameter("canonical-form",true);
i have the following xml file:
<?xml version='1.0' encoding='utf-8' ?>
<osm>
<node id="25779111" lat="50.03342" lon="5.461545"/>
<node id="25779112" lat="50.03304" lon="5.814"/>
<node id="25779119" lat="50.03395" lon="5.8255"/>
<tag k="maxspeed" v="30"/>
<tag k="maxspeed:zone" v="yes"/>
<ele k="maxspeed:zone" v="60"/>
and i reviewed some posts to know how can i update or change a value in the xml file using xpath, and idid the following :
for (int i = 1 ; i <= 2; i++) {
String expr0 = "//node[#lat='53.0334062'][#lon='8.8461545']/following-sibling::tag["+i+"]/#v";
xPath.compile(expr0);
Node s = (Node) xPath.evaluate(expr0, document, XPathConstants.NODE);
System.out.println(s);
s.setNodeValue("999");
}
but when i checked the xml file, i expected to see the change written to it, but there was no change.
please let me know how to change the value in the xml file using xPath correctly.
you need to write the document back to the disk. Here's how:
TransformerFactory transformerFactory = TransformerFactory.newInstance();
Transformer transformer = transformerFactory.newTransformer();
DOMSource source = new DOMSource(document);
String filePath = "path/to/new/file.xml";
StreamResult streamResult = new StreamResult(new File(filePath));
transformer.transform(source, streamResult);
More help here: http://download.oracle.com/javaee/1.4/tutorial/doc/JAXPXSLT4.html
Hope this helps. :)
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