DOM to XML in JAVA is not working - java

I have written the following code
DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
Document doc = docBuilder.newDocument();
// Unniversity tag
Element rootElement = doc.createElement("university");
// Unniversity attrs
Attr uniName = doc.createAttribute("name");
uniName.setNodeValue(university.name);
Attr uniLogo = doc.createAttribute("logo");
uniLogo.setNodeValue(university.pathToLogo);
Attr uniMission = doc.createAttribute("mission");
uniMission.setNodeValue(university.mission);
Attr uniVision = doc.createAttribute("vision");
uniVision.setNodeValue(university.vision);
rootElement.setAttributeNode(uniName);
rootElement.setAttributeNode(uniLogo);
rootElement.setAttributeNode(uniMission);
rootElement.setAttributeNode(uniVision);
While debugging when I check the value of doc I found following
doc = (com.sun.org.apache.xerces.internal.dom.DocumentImpl) [#document: null]
What am I doing wrong? I followed this.

In your code you have not set the contents of the document. You should add the following:
document.appendChild(rootElement);
To confirm that the document contains the XML structure you can print the following statement:\
System.out.println(document.getDocumentElement());
This will print [university : null]

Well I was making a silly mistake i.e. I donot bind/add the rootElement with doc
Updated Code:
DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
Document doc = docBuilder.newDocument();
// Unniversity tag
Element rootElement = doc.createElement("university");
doc.appendChild(rootElement); // I forgot to add this statement
// Unniversity attrs
Attr uniName = doc.createAttribute("name");
uniName.setNodeValue(university.name);
Attr uniLogo = doc.createAttribute("logo");
uniLogo.setNodeValue(university.pathToLogo);
Attr uniMission = doc.createAttribute("mission");
uniMission.setNodeValue(university.mission);
Attr uniVision = doc.createAttribute("vision");
uniVision.setNodeValue(university.vision);
rootElement.setAttributeNode(uniName);
rootElement.setAttributeNode(uniLogo);
rootElement.setAttributeNode(uniMission);
rootElement.setAttributeNode(uniVision);

Related

Batik's SVGDocument.getElementsByTagNameNS returns empty NodeList despite of namespace and tagname being correctly set

I have a part of code parsing SVG document.
String parser = XMLResourceDescriptor.getXMLParserClassName();
SAXSVGDocumentFactory factory = new SAXSVGDocumentFactory(parser);
SVGDocument svgDocument = null;
try {
//svgDocument = factory.createSVGDocument(IMAGE_SVG);
svgDocument = factory.createSVGDocument("file://", new FileInputStream(f
));
} catch (IOException e) {
System.out.println(e.getMessage());
}
NodeList gs= svgDocument.getElementsByTagNameNS("http://www.w3.org/2000/svg","g");
NodeList pathes = svgDocument.getElementsByTagNameNS("http://www.w3.org/2000/svg", "path");
For strange reason gs and pathes bear no nodes inside. While in debugger is see that svgDocument identified elementsById inside it correctly, while elementsByTagNames and elementsByTagNamesNS are empty. How to resolve that issue? How to make elements load by tag name too?
It was some issue with file loading
DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance();
docBuilderFactory.setNamespaceAware(true);
DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder();
String line = new String(Files.readAllBytes(Paths.get("path to file")), StandardCharsets.UTF_8);
Document doc = docBuilder.parse(new InputSource(new StringReader(line)));
and that document returns .getElementsByTagNameNS as wanted

I am getting null pointer exception when i get the data from xml document using web service

String name= "Nsss";
String resulturl ="http://ssss/res/get?sid="+name+"";
DocumentBuilder db = DocumentBuilderFactory.newInstance().newDocumentBuilder();
InputSource is = new InputSource();
is.setCharacterStream(new StringReader(resulturl));
Document doc = db.parse(resulturl);
System.out.println("sssssssssssssssssssssssssssssssssssssssssssssssssss"+doc.getDoctype().getTextContent());
I am getting this exception.
java.lang.NullPointerException
at com.controller.StudentsResultsController.main(ResultsController.java:130)
You should check to see what the resulturl variable is before you use it, but the other thing you need to address is: You are not using the InputSource at all. The following is likely to work better than what you have:
InputSource is = new InputSource();
is.setCharacterStream(new StringReader(resulturl));
Document doc = db.parse(is);
EDIT
The Fatal Error is caused by the following:
StringReader(resulturl) takes a string argument that must be XML, not a filename or a URL. The parser is reading the value of the string variable, resulturl, and failing immediately because an XML document may not begin with an h character.
Try changing the above to:
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
Document doc = dBuilder.parse(new InputSource(resulturl));

How to create tag with namespace prefix

I am trying to add a prefix to a tag to represent a particular namespace - as can be seen below
String envelopePrefix = "omgEnv";
String businessPrefix = "omgBS";
String namespaceURI = "http://www.w3.org/2000/xmlns/";
DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
Document doc = docBuilder.newDocument();
Element rootElement = doc.createElement("OmgeoMessageContainer");
rootElement.setAttributeNS(namespaceURI, "xmlns:" + envelopePrefix, "http://www.omgeo.com/schema/v1.0/envelope");
rootElement.setAttributeNS(namespaceURI, "xmlns:" + businessPrefix, "http://www.omgeo.com/schema/v1.0/BusinessServices");
doc.appendChild(rootElement);
Element messageParties = doc.createElementNS(namespaceURI, envelopePrefix + ":MessageParties");
rootElement.appendChild(messageParties);
Unfortunately my messageParties element is failing with the following error -
org.w3c.dom.DOMException: NAMESPACE_ERR: An attempt is made to create
or change an object in a way which is incorrect with regard to
namespaces.
How are you supposed to prefix a tag with the correct namespace definition? Event the setPrefix method throws the same error.
Thanks
I do not think you can decide the prefix for a namespace element while generating XML. I did not see any such option in the JavaDocs. To create element with namespace this should be the modification.
String namespaceURI = "http://www.w3.org/2000/xmlns/";
DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
Document doc = docBuilder.newDocument();
Element rootElement = doc.createElementNS(namespaceURI, "OmgeoMessageContainer");
doc.appendChild(rootElement);
Element messageParties = doc.createElementNS(namespaceURI, "MessageParties");
rootElement.appendChild(messageParties);
This will generate the XML with auto decided prefix for the namespaces.

xml search element by id

Can we search a element by id in xml file using dom parser, for example :
<root>
<context id="one">
<entity>
<identifier>new one</identifier>
</entity>
</context>
<context id="two">
<entity>
<identifier>second one</identifier>
</entity>
</context>
</root>
I want a node with id = "one", my code
DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder();
Document document = docBuilder.parse(new File("filename.xml"));
Element ele = document.getElementById("one");
return null,
is there any other way?
From the documentation for Document.getElementById
Note: Attributes with the name "ID" or "id" are not of type ID unless so defined.
The problem is the Document doesn't know that an attribute called id is an identifier unless you tell it. You need to set a schema on the DocumentBuilderFactory before you call newDocumentBuilder. That way the DocumentBuilder will be aware of the element types.
In the schema you will need something like this in the appropriate place:
<xs:attribute name="id" type="xs:ID"/>
You could use the javax.xml.xpath APIs in the JDK/JRE to find the element by XPath.
Example
import java.io.File;
import javax.xml.parsers.*;
import javax.xml.xpath.*;
import org.w3c.dom.*;
public class Demo {
public static void main(String[] args) throws Exception {
DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder();
Document document = docBuilder.parse(new File("filename.xml"));
XPathFactory xpathFactory = XPathFactory.newInstance();
XPath xpath = xpathFactory.newXPath();
Element element = (Element) xpath.evaluate("//*[#id='one']", document, XPathConstants.NODE);
}
}
You could instead use a third party library like Jsoup that does the job rather quite well.
File input = new File("/tmp/input.xml");
Document doc = Jsoup.parse(input, "UTF-8", "test");
And then you could use something like this:
doc.select("context#id=one")
Does that answer your question?
try and use XML - Xpath expression it is very easy
File fXmlFile = new File("filePath");
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
Document doc = dBuilder.parse(fXmlFile);
doc.getDocumentElement().normalize();
System.out.println("Root element :" + doc.getDocumentElement().getNodeName());
XPathFactory factory = XPathFactory.newInstance();
XPath xpath = factory.newXPath();
String expression;
Node node;
// 1. elements with id '1'
expression = "//context[#id='one']";
node = (Node ) xpath.evaluate(expression, doc, XPathConstants.NODE);

Create a DOM Document from an Url

the url : http://www.evemarketeer.com/api/orders/10000043/30119/xml
I tried this
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Document doc = db.parse(url.openStream());
But isn't working, anyone got any idea to create a Document with an easy method ?
Thx
This works for me (returns 28 "row" elements)
URL url = new URL("http://www.evemarketeer.com/api/orders/10000043/30119/xml");
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Document doc = db.parse(url.openStream());
NodeList nodes = doc.getElementsByTagName("row");
System.out.println(nodes.getLength() + " nodes found");

Categories