XML DOM createchild takes Node instread of Element - java

I am creating a XML using DOM as below using online examples,
DocumentBuilderFactory docfac= DocumentBuilderFactory.newInstance();
DocumentBuilder docb= docFactory.newDocumentBuilder();
Document doc = docb.newDocument();
// root
Element rootElement = (Element)doc.createElement("TEST");
doc.appendChild(rootElement); //Compiler error
...
appenchild takes Node object, not Element object. I was trying to use Node but, it seems like there is no methods exposed to set attribute, therefore, I can't really use node.
Any help would be really appreciate it.
Thanks.

Please verify the packages you've imported : import org.w3c.dom.Document and import org.w3c.dom.Element; and change docfac.newDocumentBuilder();
No need to type cast the org.w3c.dom.Element because doc.createElement("TEST") returns an object of org.w3c.dom.Element which is a sub-interface of org.w3c.dom.Node.
org.w3c.dom.Element rootElement = doc.createElement("TEST");
doc.appendChild(rootElement)

Related

Getting org.w3c.dom.DOMException: HIERARCHY_REQUEST_ERR adding root node to document

I'm trying to create a simple XML document and am receiving the above error when adding the root element to the document. I only have the one root element (the first element created for the document) and the error throws on the first append_child() call. Here is the code leading up to where the error throws (on the securityDoc.appendChild(securityDoc) call):
public Document CreateSecurityHeader() throws ParserConfigurationException {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setNamespaceAware(true);
DocumentBuilder builder = factory.newDocumentBuilder();
Document securityDoc = builder.newDocument();
try {
Element securityRoot = securityDoc.createElementNS("http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd", "wsse:Security");
securityRoot.setAttributeNS("http://www.w3.org/2000/xmlns/","xmlns:wsse", "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd");
securityRoot.setAttributeNS("http://www.w3.org/2000/xmlns/","xmlns:wsu", "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd");
securityRoot.setAttributeNS("http://www.w3.org/2000/xmlns/","xmlns:env", "http://www.w3.org/2003/05/soap-envelope");
securityRoot.setAttributeNS("http://www.w3.org/2000/xmlns/","xmlns:wss","http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd");
securityRoot.setAttribute("env:mustUnderstand", "1");
securityDoc.appendChild(securityDoc);
As this is the only Element in that document at this point, how am I getting the this error? I did have to pull in the xalan and xerces library as dependencies for this project for something else, could there be an incompatibility here?
Whoops. You append securityDoc to securityDoc.
securityDoc.appendChild(securityDoc);
I'm sure you mean this:
securityDoc.appendChild(securityRoot);
I only noticed this myself by stepping through the validation code and when it was using the node lookup tables to check whether the proposed tree structure is legal I saw that what you were appending was DOCUMENT_NODE, which is not legal to append to a DOCUMENT_NODE.

Finding Element in NodeList XML

Is there a way i can get the first Element from a NodeList? Im using org.w3c.dom to handle XML files, i have already written large parts of my program using org.w3c.dom and discovered only recently dom4j which has a method for it but i cannot use it because of backward compatibility issues with my other methods.
It is critical that i can find and pass the very first Element in my XML and it must be of type org.w3c.dom.Element , however, not even using doc.normalize(); has helped, neither did using dom4j methods to find the element and cast it into org.w3c.dom.Element as thats forbidden.
File file = new File("myXML.xml");
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dbuilder = dbFactory.newDocumentBuilder();
Document doc = dBuilder.newDocument();
doc = dBuilder.parse(file);
doc.normalize;
Element sourceElem = doc.getDocumentElement();
NodeList nodelist = sourceElem.getChildNodes();
Element elem;
if(nodeList.item(0).getNodeType() == Node.ELEMENT_NODE){
elem = (Element)nodeList.item(0);
}
Im getting NullPointerException from other methods because it cant find the element.
I need it to work in the same way this C++ code does:
XmlDocument doc = new XmlDocument();
doc.Load("myXML.xml");
XmlElement elem = (XmlElement)doc.DocumentElement.ChildNodes[0];
EDIT: OR is there a way i can cast dom4j Element back into org.w3c.dom.Element?
EDIT2: Sample XML i need to access http://pastebin.com/C3nvxhwx

How can I create a DOM Element without a document?

Working with JAXP, the "Hello world" to create an element is:
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Document doc = db.newDocument();
Element e = doc.createElement("helloElement");
// attributes, append, etc...
this makes the creation of an Element dependent of a document object. Is there any way to create an element without a particular document ? something like:
Element e = DomDocument.createElement("helloElement"); //static method or so ...
return e;
Implementing the Element interface is way too much than necessary!
the purpose is to get a DOM Element from a POJO without the need to pass a document
any suggestions ?
Is there any way to create an element without a particular document?
No. The way the DOM is designed the Document is a factory for all the other objects, and those objects can only exist within the context of a particular Document. So you're already using the correct approach by creating an empty document from the DocumentBuilder.
the purpose is to get a DOM Element from a POJO without the need to pass a document
You can create your own Document within the POJO and use that to create elements, but then if a caller of your method wants to add the returned Element to their own Document they will first have to "adopt" it by calling adoptNode, as a Document is only allowed to contain nodes that it "owns".

How to append xml nodes (as a string) into an existing XML Element node (only using java builtins)?

(Disclaimer: using Rhino inside RingoJS)
Let's say I have a document with an element , I don't see how I can append nodes as string to this element. In order to parse the string to xml nodes and then append them to the node, I tried to use documentFragment but I couldn't get anywhere. In short, I need something as easy as .NET's .innerXML but it's not in the java api.
var dbFactory = javax.xml.parsers.DocumentBuilderFactory.newInstance();
var dBuilder = dbFactory.newDocumentBuilder();
var doc = dBuilder.newDocument();
var el = doc.createElement('test');
var nodesToAppend = '<foo bar="1">Hi <baz>there</baz></foo>';
el.appendChild(???);
How can I do this without using any third party library ?
[EDIT] It's not obvious in the example but I'm not supposed to know the content of variable 'nodesToAppend'. So please, don't point me to tutorials about how to create elements in an xml document.
You can do this in java - you should be able to derive the Rhino equivalent:
DocumentBuilderFactory dbFactory = javax.xml.parsers.DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
Document doc = dBuilder.newDocument();
Element el = doc.createElement('test');
doc.appendChild(el);
String xml = "<foo bar=\"1\">Hi <baz>there</baz></foo>";
Document doc2 = builder.parse(new ByteArrayInputStream(xml.getBytes()));
Node node = doc.importNode(doc2.getDocumentElement(), true);
el.appendChild(node);
Since doc and doc2 are two different Documents the trick is to import the node from one document to another, which is done with the importNode api above
I think your question is like this question and there is answer on it :
Java: How to read and write xml files?
OR see this link http://www.mkyong.com/java/how-to-create-xml-file-in-java-dom/

Java XML parser?

I'm currently converting a program I wrote in Visual Basic .NET (the 2005 variety) into Java. It used built-in XML methods to parse and generate the user's saved data, does Java have an equivalent feature built in or am I going to have to change file processing implementations? (I'd rather not, there's a lot of code I'd have to change.)
Yes, Java can parse XML. Here's an example that takes in a String that contains XML and builds a Document object out of it:
DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
InputSource inputSource = new InputSource(new StringReader(xml));
Document document = documentBuilder.parse(inputSource);
You can then use the XPath API to query the dom. Here's a tutorial/writeup about it.
As far as serializing objects to XML, the official implementation is JAXB and it is part of Java since 1.6. Here's a simple example. It will let you serialize and deserialize to and from XML.
You can also create a DOM object manually and add nodes to it, but it's a little more tedious:
DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
Document document = documentBuilder.newDocument();
Element rootNode = document.createElement("root");
Element childNode = document.createElement("child");
childNode.setTextContent("I am a child node");
childNode.setAttribute("attr", "value");
rootNode.appendChild(childNode);
document.appendChild(rootNode);
I'm assuming that you mean that the properties/structure was generated through the classes/beans themselves? If so, then the answer is no [without an third party component]. I've used XStream before, and that is about the closest that I've gotten to .NET's XML Class serialization.

Categories

Resources