How can I create a DOM Element without a document? - java

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".

Related

Extracting elements from an HTTP XML response--HTTP Client & Java

So I've gotten help from here already so I figured why not try it out again!? Any suggestions would be greatly appreciated.
I'm using HTTP client and making a POST request; the response is an XML body that looks like the following:
<?xml version="1.0" encoding="UTF-8"?>
<CartLink
xmlns="http://api.gsicommerce.com/schema/ews/1.0">
<Name>vSisFfYlAPwAAAE_CPBZ3qYh</Name>
<Uri>carts/vSisFfYlAPwAAAE_CPBZ3qYh</Uri>
</CartLink>
Now...
I have an HttpEntity which is
[HttpResponse].getEntity().
Then I get a String representation of the response (which is XML in this case) by saying
String content = EntityUtils.toString(HttpEntity)
I tried following some of the suggestions on this post: How to create a XML object from String in Java? but it did not seem to work for me. When I built up the document it still appeared to be null.
MY END GOAL here is just to get the NAME field.. i.e. the "vSisFfYlAPwAAAE_CPBZ3qYh" part. So do I want to build up a document and then extract it...? Or is there a simpler way? I've been trying different things and I can't seem to get it to work.
Thanks for all of the help guys, it is most appreciated!!
Instead of trying to extract the value with string manipulation, try to use Java's inbuilt ability to parse XML. That's a much better approach. Http Components returns responses in an XML format - there's a reason for that. :)
Here's probably one way to solve your problem:
// Parse the response using DocumentBuilder so you can get at elements easily
DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder();
Document doc = docBuilder.parse(response);
Element root = doc.getDocumentElement();
// Now let's say you have not one, but 'n' nodes that contain the value
// you're looking for. Use NodeList to get a list of all those nodes and just
// pull out the tag/attribute's value you want.
NodeList nameNodesList = doc.getElementsByTagName("Name");
ArrayList<String> nameValues = null;
// Now iterate through the Nodelist to get the values you want.
for (int i=0; i<nameNodesList.getLength(); i++){
nameValues.add(nameNodesList.item(i).getTextContent());
}
The ArrayList "nameValues" will now hold every single value contained within "Name" tags. You could also create a HashMap to store a key value pair of Nodes and their respective text contents.
Hope this helps.

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/

How to build DOM tree from XML file by ourself, i.e. don't use DocumentBuilder.parse(xml)?

Suppose there is a simple XML file as below:
<a>
<b>hello</b>
<c>world</c>
</a>
I want to create a DOM tree, without using the parser provided by Java library ( I do want to use other APIs and data structures, like Element). I am kind of familiar with the lexing(tokenization) part, but how to use the tokens to build the tree ?
The tree creating algorithm is something I learnt from data structure classes. The problem is how to utilize the given DOM framework in Java library? like Element, or Node, or DOM APIs which can help insert new nodes to the DOM tree.
Is there any exiting examples that I can learn from ?
Start off from DocumentBuilderFactory, create a DocumentBuilder and from this create a new Document object. From there, Document has methods to add elements, attributes, etc so you can use these methods to generate a document.
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
//dbf.setNamespaceAware(true); //If you need namespace support turn this on, it is off by default
Document doc = dbf.newDocumentBuilder().newDocument();
//Add a root element
Element rootElement = doc.createElement("root");
doc.appendChild(rootElement);
Attr att = doc.createAttribute("my-attribute");
att.setValue("value");
rootElement.appendChild(att);

XML DOM createchild takes Node instread of Element

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)

Xpath returns empty element object

I have an xml document as a string without any namespace and I want to parse it using Java, JDOM and XPath, and create a object tree. Since XPAth always requires a prefix and a namespace to query, I added namespace and a prefix to the root and then later to the node I want to get, but I see Xpath requires a namespace in every node in the document but only in the root.
So in the beginning is there a way to add the namespace to all of the elements in the document object so my xpath query works correct?
There should be other mistakes and bad approches in the code as well. Will be glad for any ideas.
String response="myXmlString"
ByteArrayInputStream stream = new ByteArrayInputStream(
response.getBytes());
SAXBuilder builder = new SAXBuilder();
Document doc = builder.build(stream);
org.jdom.Element request=(org.jdom.Element) doc.getRootElement();
request.setNamespace(Namespace.getNamespace("myNamespace"));
createRequest(request);
And then
public Request createRequest(Element requestXML) {
Request request = new Request();
requestXML.detach();
Document doc = new Document(requestXML);
XPath xpath = XPath.newInstance(myExpression);
xpath.addNamespace("m", doc.getRootElement().getNamespaceURI());
xpath.selectSingleNode(doc);
}
this last line returns empty, it is not null but it throws jdom exception inside.
XPath and XML do NOT require namespace. Go back to your original XML and remove any namespace/prefix hackery in your code.

Categories

Resources