I am trying to create a simple Document with Jdom.
I strictly followed the instructions given on
https://www.tutorialspoint.com/java_xml/java_dom_create_document.htm
I cannot understand why, no matter what I do, I end up with a [document:null].
This is my code :
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.DocumentBuilder;
import org.w3c.dom.*;
import javax.xml.parsers.*;
import java.io.*;
import java.util.*;
import org.jdom2.*;
import org.w3c.dom.Attr;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
public class Network {
public Document SetToXml() throws Exception {
Document doc = null;
try {
DocumentBuilderFactory DBF =
DocumentBuilderFactory.newInstance();
DocumentBuilder DB = DBF.newDocumentBuilder();
doc = DB.newDocument();
Element root = doc.createElement("network");
root.setAttribute("name", Name);
doc.appendChild(root);
}
}
}
When I inspect the doc variable, it always contains [document:null].
Is there any way out or should I give up ?
Thanks
I would say, no need to worry :)
The "[document:null]" string which your debugger is showing you is only the toString() - representation of the document object. I do not yet understand, why it actually looks like this, but I verified that regardless of this, the document actually has the "netwrok" element you specified and also the name attribute you are assigning to it.
Related
I'm trying with this attempt to produce an xml based on the one given, joining values of same TagName.
For example this is what I've done so far:
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpression;
import javax.xml.xpath.XPathExpressionException;
import javax.xml.xpath.XPathFactory;
import org.w3c.dom.Document;
import org.xml.sax.SAXException;
public class TestXPath {
public static void main(String[] args) throws SAXException, IOException, ParserConfigurationException, XPathExpressionException {
String xml =
"<ROOT>" +
" <coolnessId>9</coolnessId>" +
" <cars id=\"3\">0</cars>" +
" <cars id=\"2\">1</cars>" +
" <cars id=\"1\">2</cars>" +
"</ROOT>";
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setNamespaceAware(true);
Document doc = factory.newDocumentBuilder().parse(new ByteArrayInputStream(xml.getBytes(StandardCharsets.UTF_8)));
XPath xpath = XPathFactory.newInstance().newXPath();
///XPathExpression expr = xpath.compile("concat(//ROOT/cars,'-',//ROOT/coolnessId)");//concat(//ROOT/cars)
XPathExpression expr = xpath.compile("concat(//ROOT/cars,'-')");//concat(//ROOT/cars)
// XPathExpression expr = xpath.compile( "concat(//*[contains(name(), 'cars')],'')");
System.out.println(expr.evaluate(doc, XPathConstants.STRING));
}
}
This code produces:
0-
Now this is what should be:
2-1-0
As you can see the values follow the attribute "id" of each "cars" tag.
I've rearrenged many times but can't achieve my result.
Please keep in mind I'm on a very old enviroment such as Java 1.4 runtime.
I think it's going to be simplest to retrieve the nodes using XPath, and then concatenate the string values in Java code.
Any other solution involves upgrading your technology: XSLT, XPath 2.0+, etc, and that isn't going to be easy on a JDK 1.4 platform.
I have multiple threads trying to read the same DOM object and runs simultaneously.
But I heard that, DOM is not thread safe and somewhere I read that if we clone the document, that cloned document will be thread safe.
this is what I wanted to try
import java.io.File;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
public class Demo {
public static void main(String[] args) throws Exception {
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Document originalDocument = db.parse(new File("input.xml"));
Node originalRoot = originalDocument.getDocumentElement();
Document copiedDocument = db.newDocument();
Node copiedRoot = copiedDocument.importNode(originalRoot, true);
copiedDocument.appendChild(copiedRoot);
}
}
Now I will allow my threads to read from copiedDocument, instead of originalDocument.
So, Now Do my code runs in thread safe or not? Could anyone please confirm.
I already have downloaded wordnet2.0 full, but i am not getting how to use it as a graph because it consists of multiple RDF files. I want to use wordnet2.0 ontology as a graph in Eclipse. The following is the snippet of code that i am using for loading a ontology as a graph. I also want to know, Am i going in a right direction???
URIFactory factory = URIFactoryMemory.getSingleton();
URI graph_uri = factory.createURI("http://graph/");
G graph = new GraphMemory(graph_uri);
String fpath ="D:/Workspace/SSM/src/wordnet-wordsensesandwords.rdf";
GDataConf graphconf = new GDataConf(GFormat.RDF_XML, fpath);
GAction actionRerootConf = new GAction(GActionType.REROOTING);
GraphConf gConf = new GraphConf();
gConf.addGDataConf(graphconf);
gConf.addGAction(actionRerootConf);
// GraphLoaderGeneric.populate(graphconf, graph);
GraphLoaderGeneric.load(gConf, graph);
// General information about the graph
System.out.println(graph.toString());
http://wordnet.princeton.edu/wordnet/download/old-versions/
You can use this link to download the ontology and may use apache jena to query this
Once you have the results, you can represent it in the form of graph
You may also download wordnet in RDF format and can display it as graph using Protege tool
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.net.URL;
import nu.xom.Builder;
import nu.xom.ParsingException;
import nu.xom.ValidityException;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpressionException;
import javax.xml.xpath.XPathFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
import edu.mit.jwi.Dictionary;
import edu.mit.jwi.IDictionary;
import edu.mit.jwi.item.IIndexWord;
import edu.mit.jwi.item.ISynset;
import edu.mit.jwi.item.IWord;
import edu.mit.jwi.item.IWordID;
import edu.mit.jwi.item.POS;
public class Main
{
public static void main(String[] args)
{
try
{
FileInputStream file = new FileInputStream(new File("c:\\employees.xml"));
DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = builderFactory.newDocumentBuilder();
Document xmlDocument = builder.parse(file);
XPath xPath = XPathFactory.newInstance().newXPath();
System.out.println("*************************");
String expression = "/Employees/Employee[#emplid='3333']/job";
System.out.println(expression);
String job = xPath.compile(expression).evaluate(xmlDocument);
System.out.println(job);
System.out.println("*************************");
String path = "C:\\Program Files\\WordNet\\2.1\\dict";
URL url = new URL("file", null, path);
IDictionary dict = new Dictionary(url);
dict.open();
IIndexWord idxWord = dict . getIndexWord (job, POS. NOUN );
IWordID wordID = idxWord . getWordIDs ().get (0) ;
IWord word = dict . getWord ( wordID );
ISynset synset= word.getSynset();
for (IWord w : synset.getWords())
System.out.println(w.getLemma());
}
catch(Exception a)
{
System.out.println(a);
}
}
}
This is a sample code in which wornet can be queried for getting the synonyms of the word job from wordnet and using it to find similar terms like job from the RDF graph.
I have only worked with wornet for capturing related terms and hypernyms. Hope this may help
i developed a code that parses an xml file and returns result in a frame in netbeans .The code runs successfully from netbeans but when exporting the project into jar file it shows nothing .Please ,if you have ideas ,i will be thankful if you help me .Here is the code i used for parsing .
import java.io.IOException;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpressionException;
import javax.xml.xpath.XPathFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.xml.sax.SAXException;
public class Parsing {
String a = null;
public static void main(String a) throws
ParserConfigurationException, SAXException, IOException,
XPathExpressionException {
a = getElem(a);
}
public static String getElem(String a) throws ParserConfigurationException, SAXException, XPathExpressionException, IOException {
String file = "src/xml/read.xml";
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
dbf.setNamespaceAware(false);
DocumentBuilder db = dbf.newDocumentBuilder();
Document doc = db.parse(file);
XPath xpath = XPathFactory.newInstance().newXPath();
Node CustomerId = (Node) xpath.evaluate("//Operation[#name='Read' and #modifier='Customer']/ParameterList/StringParameter[#name='CustomerId']/text()",
doc.getDocumentElement(), XPathConstants.NODE);
a = CustomerId.getNodeValue();
return a;
}
}
when calling the method getElem(a) from another frame it shows me the value of a in a textbox ,but when exporting the project into a jar file it doesn't show me anything !
First thing that strikes me is the use of relative path to your XML resource. It seems you rely on existence of a file in a directory relative to your working dir.
The src directory will not exist at run time. This suggests that the XML file is an em ebbed resource, and as such, can't get accessed as a file would be if it lived on the file system.
Instead you want to use something like...
getClass().getResourceAsStream("/xml/read.xml")
And pass the resulting InputStream to DocumentBuilder. Don't forget to close it
here is the modified code that worked with jar file :)
import java.io.IOException;
import java.io.InputStream;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpressionException;
import javax.xml.xpath.XPathFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
public class Parsing {
String a = null;
private static final String TEST_XML = "/xml/read.xml";
public static void main(String a) throws
ParserConfigurationException, SAXException, IOException,
XPathExpressionException {
a = getElem(a);
}
protected static InputSource getTestXMLInputSource() {
InputStream is = Parsing.class.getResourceAsStream(TEST_XML);
is = Parsing.class.getResourceAsStream(TEST_XML);
return new InputSource(is);
}
public static String getElem(String a) throws ParserConfigurationException, SAXException, XPathExpressionException, IOException {
final InputSource source = getTestXMLInputSource();
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
dbf.setNamespaceAware(false);
DocumentBuilder db = dbf.newDocumentBuilder();
Document doc = db.parse(source);
XPath xpath = XPathFactory.newInstance().newXPath();
Node CustomerId = (Node) xpath.evaluate("//Operation[#name='Read' and #modifier='Customer']/ParameterList/StringParameter[#name='CustomerId']/text()",
doc.getDocumentElement(), XPathConstants.NODE);
a = CustomerId.getNodeValue();
return a;
}
}
import java.io.ByteArrayInputStream;
import java.io.IOException;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
public class modifyXML {
public static void modify(StringBuffer XMLBuffer) throws IOException, ParserConfigurationException, SAXException{
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Document doc = db.parse(new ByteArrayInputStream(XMLBuffer.toString().getBytes()));
Element rootNode = doc.getDocumentElement();
NodeList priceList = rootNode.getElementsByTagName("price");
priceList.item(0).setTextContent("190");
NodeList inStockList = rootNode.getElementsByTagName("id_product_attribute");
inStockList.item(0).setTextContent("100");
}
}
I am trying to modify an XML file and then put it all back together. I have managed with the modifying part, but I can not get the XML file back together. The result can be either a String or a StringBuffer.
What is the best/easiest way to do this?
Use a Transformer as described by WhiteFang34 in XML Document to String.
Official Java Tutorials: Writing Out a DOM as an XML File (just make StreamResult Wrap something else such as StringWriter).
Update:
Less known, shorter alternative by ykaganovich based on Load / Save objects: