Java DOM, namespace / version problem - java

Im in the process of creating XML as a Node for a RMI program I am developing but I have run across a problem. I can create the XML using DOM but I am struggling to add namespace and version to the top of my XML. I have tried using setAttribute and setAttributeNS but at the moment lost in what else I can do.
The java code to create the element is:
DocumentBuilderFactory dbfac = DocumentBuilderFactory.newInstance();
DocumentBuilder docBuilder = dbfac.newDocumentBuilder();
Document doc = docBuilder.newDocument();
Node root = doc.createElement("Request");
doc.appendChild(root);
//code ommited
The result I get currently is:
<Request>
<Identification>
<UserID>user</UserID>
<Password>pass</Password>
</Identification>
</Request>
In the request section I need it to look like:
<Request xsi:noNamespaceSchemaLocation="URL" Version="1.0">
Any help will be appreciated to help solve this issue!
Thanks

I think you'd want something like:
...
Element root = doc.createElement("Request");
root.setAttributeNS("http://www.w3.org/2001/XMLSchema-instance", "xsi:noNamespaceSchemaLocation", "URL");
root.setAttribute("Version", "1.0");
doc.appendChild(root);
...
Defining root as an Element gives you the .setAttribute* methods.
This would give you
<Request Version="1.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="URL"/>
I know that includes a bit more, but the xmlns:xsi attribute is needed so that the xsi namespace is defined.

Related

Why are xmlns="" added to element in Java automatically?

I am creating an XML file using Java.
I created root node using createElemenNS() to createh root node with namespace.
Element root = doc.createElementNS("http://www.myorc.com/schemas", "InvConf");
Then I created a node using createElement() and added it to root node. This node is automatically added with namespace like below.
Element invList = doc.createElement("InvList");
root.appendChild(invList);
<InvConf xmlns="http://www.myorc.com/schemas">
<InvList xmlns="">
...
</InvList>
<InvList xmlns="">
...
</InvList>
<InvList xmlns="">
...
</InvList>
</InvConf>
How to avoid adding the namespace to child nodes ?
I want the final XML to be like the following
<InvConf xmlns="http://www.myorc.com/schemas">
<InvList>
...
</InvList>
<InvList>
...
</InvList>
<InvList>
...
</InvList>
</InvConf>
Found that issues is coming only when xmlparserv2.jar is in CLASSPATH. This is required by some parts for the application. How to resolve this ?
The xmlns="" were added because your child is not in a namespace, and your parent is. To change that, put it in the namespace at the time you create the element.
Change the
createElement("InvList");
To the correct namespace.
As pointed out in comments xmlns="" means that element doesn't have any namespace. E.g. from XML parser point of view following two documents are identical:
<ns:root xmlns:ns="http://namespace.com">
<child/>
</ns:root>
and
<root xmlns="http://namespace.com">
<child xmlns=""/>
</root>
To avoid creation of xmlns="" in elements not belonging to any namespace you can create prefix on upper level element:
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
dbf.setNamespaceAware(true);
DocumentBuilder db = dbf.newDocumentBuilder();
Document doc = db.newDocument();
Element root = doc.createElementNS("http://namespace.com", "root");
root.setPrefix("ns");
Element child = doc.createElementNS("", "child");
root.appendChild(child);
doc.appendChild(root);
This code will create following XML:
<ns:root xmlns:ns="http://namespace.com">
<child/>
</ns:root>
Alternatively you can use following syntax to achieve same result:
Document doc = db.newDocument();
Element root = doc.createElementNS("http://namespace.com", "ns:root");
Element child = doc.createElementNS("", "child");
root.appendChild(child);
doc.appendChild(root);
When commenting out line root.setPrefix("ns"); or creating element without prefix (doc.createElementNS("http://namespace.com", "root");) following XML will be generated:
<root xmlns="http://namespace.com">
<child xmlns=""/>
</root>

How to remove duplicate XML declaration

I am receiving following XML response via Jersey client
<?xml version="1.0" encoding="UTF-8" standalone="yes"?><aaa><bbb key="Data"><?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<my-data xsi:noNamespaceSchemaLocation="MyData.xsd" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<data name="abc" uniqueId="4fe95637-a381-4e0c-bf7f-49f794df5f23">
<variable var1="xyz" value="44"/>
</data>
</my-data>
</bbb></aaa>
I am saving this as an XML file and getting 'premature end of file' error during parsing, since the XML is malformed (duplicate XML declarations)...is there a way to remove following duplicate entry from the output?
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
Following is my Java code snippet:
String output = response.getEntity(String.class);
file = writeResponseToFile(output,"MyData.xml");
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
dbf.setNamespaceAware(true);
DocumentBuilder db = dbf.newDocumentBuilder();
Document document = db.parse(file); //Error
Ideally, you should fix the problem at the source. What you're receiving is not XML because having more than one XML declaration violates XML's basic grammar, making the data not well-formed.
If it is impossible to properly fix the problem at the source, and you wish to attempt repair, you have to treat that data as text, not XML, until you remove the extra XML declaration (via text-level operations, not XML parsing).
Fix the xml that you are receiving. You receive two declarations in the xml.
The xml is malformed. Remember in Jersey, you can receive files on JSON, xml, html, etc, via annotations, with #Produces.
And remember that you have xml validators on internet, to valid your xml.
Regards.

Trouble Creating org.w3c.dom.Document from xml string in java

I am trying to create an org.w3c.dom.Document object from an xml string. I have followed what many have suggested in other questions but the document ends up empty. What is wrong with the following code?
DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
Document doc = docBuilder.parse(new InputSource(new StringReader(response.getResponseText())));
And the xml text in the string looks like the following (this comes from response.getResponseText())
<s:Envelope xmlns:s="http://www.w3.org/2003/05/soap-envelope" xmlns:a="http://www.w3.org/2005/08/addressing">
<s:Header>
<a:Action s:mustUnderstand="1">http://www.blah.com/ns/2006/05/01/webservices/123/TokenManagement_1/CreateServiceToken_1_Reply</a:Action>
<CacheResponse xsi:type="DoNotStoreCacheResponse" xmlns="http://www.blah.com/ns/2008/03/01/webservices/123/Cache_1" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<Date>2012-09-04T15:35:06.8116593Z</Date>
<DoNotStore />
</CacheResponse>
<a:RelatesTo>ba04425d-d93e-4a70-a134-ab8e29d5345c}</a:RelatesTo>
</s:Header>
<s:Body>
<CreateServiceToken_Response_1 xmlns="http://www.blah.com/ns/2006/05/01/webservices/123/TokenManagement_1" xmlns:global="http://www.blah.com/ns/2006/05/01/webservices/123/Common_1">
<Expiration>2012-09-04T17:04:19.1834228Z</Expiration>
<global:Token>3DEC2723A01047D1590544CBA5BA1E30326535E609DC1E6FAC5C659BC3B8A693BB054834A58B235037ED830CD05784DB176A62309AEB4B608C6F0B5B3F13ADE0EC56BE9F822ACFA3B549D4427D89BF030BFF48BA671DCAEB49940EFEBDEBFB71</global:Token>
</CreateServiceToken_Response_1>
</s:Body>
Can anyone see what is wrong with my code? I ultimately just want to run a couple of xpath queries on the document...
I would suggest to start with setting docFactory.setNamespaceAware(true);, otherwise the parsing, the DOM built and the XPath implementation will not be able to work with XML with namespaces as you have posted.

how to insert value into xml?

I am really new to XML and JDOM so I have a noob question, sorry for that. I have a XML file and I want to insert value into it. My XML file is like that;
<?xml version="1.0"?>
<message>
<header>
<messageType> </messageType>
<sendFrom> </sendFrom>
<HostName> </HostName>
<sendTo> </sendTo>
<receiverName> </receiverName>
<date> </date>
</header>
<body>
</body>
</message>
So what I want is for example is to add value between <sendTo> </sendTo> and also I want to add <A> data </A> between <body> </body>. Can you please tell me how to do that ?
Thanks a lot.
http://www.cafeconleche.org/books/xmljava/chapters/ch14s04.html
http://www.java2s.com/Code/Java/XML/MakeupandwriteanXMLdocumentusingDOM.htm
If you use dom,you can do it as follows;
DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
Document doc = docBuilder.parse(inputFile);
Node messageType= doc.getElementsByTagName("messageType").item(0);//zero tells the order in the xml
messageType.setTextContent("SMS");
I'd recommend using XStream for XML handling.
Here, is the link to a 2 minute tutorial: http://x-stream.github.io/tutorial.html

How to remove encoding="UTF-8" standalone="no" from xml Document object in Java

I want to create XML in Java.
DocumentBuilderFactory dbfac = DocumentBuilderFactory.newInstance();
DocumentBuilder docBuilder;
docBuilder = dbfac.newDocumentBuilder();
Document doc = docBuilder.newDocument();
but Java automatically creates declaration like this
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
How can I remove encoding="UTF-8" standalone="no" so it will be
<?xml version="1.0"?>
Thanks!
Why do you need to remove an encoding? But..
doc.setXmlStandalone(true);
will erase standalone="no"
transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
This would resolve your issue, verified at JDK 6
I think there is no legal way to exclude theese attributes from generation.
But after it's generated you can use XSLT to remove this.
I think this is a good way.

Categories