How to get specified roots from xml? [closed] - java

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
I have XML file like below
<?xml version="1.0" encoding="utf-8"?>
<Movies>
<servername>
raaja
</servername>
<moviename>
xyz
</moviename>
<city>
Hyd
</city>
<theatername>
abc
</theatername>
<noofreels>
16
</noofreels>
<aspectratio>
216
</aspectratio>
</Movies>
I want the values of tags servername and theatername. Rest I dont want. How to get these using java. Is it possible to get the value using tagnames.

One way to accomplish this is to use the DOM parser included with the JDK. For example:
import org.w3c.dom.Document;
import org.xml.sax.InputSource;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import java.io.StringReader;
...
// Creates a new DOM parser instance.
DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
// Parses XML and creates a DOM document object.
// The XML variable is your XML document above stored as a string, but you could
// easily read the contents from a file or database too.
Document document = documentBuilder.parse(new InputSource(new StringReader(XML)));
// Get the text content of <theatername> using the DOM API and print it to stdout.
String theaterName = document.getElementsByTagName("theatername").item(0).getTextContent().trim();
System.out.println(theaterName);
Using StAX:
XMLInputFactory xmlInputFactory = XMLInputFactory.newInstance();
XMLStreamReader xmlStreamReader = xmlInputFactory.createXMLStreamReader(new StringReader(XML));
String theaterName = null;
while (xmlStreamReader.hasNext()) {
if (xmlStreamReader.next() == XMLStreamConstants.START_ELEMENT) {
if ("theatername".equals(xmlStreamReader.getLocalName())) {
theaterName = xmlStreamReader.getElementText().trim();
}
}
}
System.out.println(theaterName);

Related

Java Print XML to console [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 5 years ago.
Improve this question
I have this code:
import java.net.URL;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;
public class Main {
private static Document loadTestDocument(String url) throws Exception {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setNamespaceAware(true);
return factory.newDocumentBuilder().parse(new URL(url).openStream());
}
public static void main(String[] args) throws Exception {
Document doc = loadTestDocument("https://www.w3schools.com/xml/note.xml");
System.out.println(doc.getElementsByTagName("note").item(0).getChildNodes().item(0).getNodeValue());
}
}
and as as far as I'm concerned this should print node text to java console, but it seems to print nothing... There's no error or anything.
What am I doing wrong?
Zero item is note. It has no value.Use above code to print Tove
System.out.println(doc.getElementsByTagName("note").item(0).getChildNodes().item(1).getTextContent());
Try this.
Document doc = loadTestDocument("https://www.w3schools.com/xml/note.xml");
doc.getDocumentElement().normalize();
Element element =(Element)doc.getElementsByTagName("note").item(0);
System.out.println(element.getElementsByTagName("to").item(0).getTextContent());
System.out.println(element.getElementsByTagName("from").item(0).getTextContent());
Output:
Tove
Jani
Do the following to get text content
doc.getElementsByTagName("note").item(0).getChildNodes().item(0).getTextContent()
EDIT
Try this, there are some empty nodes.
int i;
for(i = 0; i < doc.getElementsByTagName("note").item(0).getChildNodes().getLength(); i++){
System.out.println(doc.getElementsByTagName("note").item(0).getChildNodes().item(i).getTextContent());
}
With another api Jsoup, we can parse the xml and print entire xml as string on console
Try this out with below snippet:
org.jsoup.nodes.Document document = Jsoup.parse(new URL("https://www.w3schools.com/xml/note.xml"), 5000);
System.out.println("XML content : "+document.html());
Output:
<note>
<to>
Tove
</to>
<from>
Jani
</from>
<heading>
Reminder
</heading>
<body>
Don't forget me this weekend!
</body>
</note>

how to create a xml structure programatically in java [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
The community reviewed whether to reopen this question 1 year ago and left it closed:
Original close reason(s) were not resolved
Improve this question
i want to create a xml structure programatically in java
the structure is like this
<?xml version="1.0" encoding="UTF-8"?>
<System token="com.test.dummy">
<Parameter token="xyz">
<Value>4</Value>
</Parameter>
</System>
i have to create a temporary file and then insert this data in the file.
I am new to this area, can someone help me.
Use DOMParser best way to write xml in java
http://docs.oracle.com/cd/B13789_01/appdev.101/b12024/oracle/xml/parser/v2/DOMParser.html
import java.io.File;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import org.w3c.dom.Attr;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
public class WriteXMLFile {
public static void main(String argv[]) {
try {
DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
// root elements
Document doc = docBuilder.newDocument();
Element rootElement = doc.createElement("company");
doc.appendChild(rootElement);
// staff elements
Element staff = doc.createElement("Staff");
rootElement.appendChild(staff);
// set attribute to staff element
Attr attr = doc.createAttribute("id");
attr.setValue("1");
staff.setAttributeNode(attr);
// shorten way
// staff.setAttribute("id", "1");
// firstname elements
Element firstname = doc.createElement("firstname");
firstname.appendChild(doc.createTextNode("yong"));
staff.appendChild(firstname);
// lastname elements
Element lastname = doc.createElement("lastname");
lastname.appendChild(doc.createTextNode("mook kim"));
staff.appendChild(lastname);
// nickname elements
Element nickname = doc.createElement("nickname");
nickname.appendChild(doc.createTextNode("mkyong"));
staff.appendChild(nickname);
// salary elements
Element salary = doc.createElement("salary");
salary.appendChild(doc.createTextNode("100000"));
staff.appendChild(salary);
// write the content into xml file
TransformerFactory transformerFactory = TransformerFactory.newInstance();
Transformer transformer = transformerFactory.newTransformer();
DOMSource source = new DOMSource(doc);
StreamResult result = new StreamResult(new File("C:\\file.xml"));
// Output to console for testing
// StreamResult result = new StreamResult(System.out);
transformer.transform(source, result);
System.out.println("File saved!");
} catch (ParserConfigurationException pce) {
pce.printStackTrace();
} catch (TransformerException tfe) {
tfe.printStackTrace();
}
}
}
see this http://www.mkyong.com/java/how-to-create-xml-file-in-java-dom/
You can also use StringBuilderto form your xml struture. StringBuilder is light weight but does not know XML so doesn't validate structure at all.But its worth going for it because of its simplicity.
StringBuilder xmlBuilder = new StringBuilder("<?xml version="1.0" encoding="UTF-8"?>");
xmlBuilder.append("<System token=\"com.test.dummy\">");
xmlBuilder.append("<Parameter token=\"xyz\">").append("<Value>4</Value>");
xmlBuilder.append("</Parameter>");
xmlBuilder.append("</System>");
xmlBuilder.toString();
You can also make your elements accept dynamic values.
Make sure your xml document structure is correct

How to get the value of a specific XML tag using StaX [duplicate]

This question already has an answer here:
Closed 10 years ago.
Possible Duplicate:
How to use StaX
Hey guys so I have an XML file and I want Java to spit out the value of a specific tag. For example here is my XML:
<?xml version="1.0"?>
<dennis>
<hair>brown</hair>
<pants>blue</pants>
<gender>male</gender>
</dennis>
So let's say I want Java to spit out the value of "gender" is there code I could use like
XMLStreamReader.goToTag("gender");
System.out.println(XMLStreamReader.getLocalName());
You could do the following:
StreamSource xml = new StreamSource("input.xml");
XMLStreamReader xsr = xif.createXMLStreamReader(xml);
xsr.nextTag();
while(!xsr.getLocalName().equals("gender")) {
xsr.nextTag();
}
XPath APIs
You could also use the javax.xml.xpath APIs:
package forum12062255;
import java.io.StringReader;
import javax.xml.xpath.*;
import org.xml.sax.InputSource;
public class XPathDemo {
private static final String XML = "<dennis><hair>brown</hair><pants>blue</pants><gender>male</gender></dennis>";
public static void main(String[] args) throws Exception {
XPathFactory xpf = XPathFactory.newInstance();
XPath xPath = xpf.newXPath();
InputSource inputSource = new InputSource(new StringReader(XML));
String result = (String) xPath.evaluate("//gender", inputSource, XPathConstants.STRING);
System.out.println(result);
}
}
Guitarroka.
When I started my studying of XML parsing with Java I have followed this tutorial.
Using STaX you will need something like this (won't post full code list):
if (event.asStartElement().getName().getLocalPart().equals("gender"))
If you insist on getting one specific tag value, you should look through DOM parser, it builds a tree from XML document, so you will be able to access element "gender" (examples of DOM are listed in link below).
Good

Cloning dom.Document object

My purpose is to read xml file into Dom object, edit the dom object, which involves removing some nodes.
After this is done i wish to restore the Dom to its original state without actually parsing the XML file.
Is there anyway i can clone the dom object i obtained after parsing the xml file for the first time. the idea is to avoid reading and parsing xml all the time, just keep a copy of original dom tree.
You could use importNode API on org.w3c.dom.Document:
Node copy = document.importNode(node, true);
Full Example
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);
}
}
TransformerFactory tfactory = TransformerFactory.newInstance();
Transformer tx = tfactory.newTransformer();
DOMSource source = new DOMSource(doc);
DOMResult result = new DOMResult();
tx.transform(source,result);
return (Document)result.getNode();
This would be the Java 1.5 solution for making a copy of the DOM document. Take a look at Transformer Factory and Transformer
you could clone a tree or only the node with DOMs cloneNode(boolean isDeepCopy) API.
Document originalDoc = parseDoc();
Document clonedDoc = originalDoc.cloneNode(true);
unfortunately, since cloneNode() on Document is (according to API) implementation specific, we have to go for a bullet-proof way, that is, create a new Document and import cloned node's from the original document:
...
Document clonedDoc = documentFactory.newDocument();
cloneDoc.appendChild(
cloneDoc.importNode(originalDoc.getDocumentElement(), true)
);
note that none of operations are thread-safe, so either use them only locally, or Thread-Local or synchronize them.
I would stick with the second suggestion with TransformerFactory.
With importNode you don't get a full copy of the document.
The header isn't copied.
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<?aid style="50" type="snippet" readerVersion="6.0" featureSet="257" product="8.0(370)" ?>
<?aid SnippetType="PageItem"?><Document DOMVersion="8.0" Self="d">
This would not return the above because this isn't copied. It's will be using what ever your new document contain.
<?xml version="1.0" encoding="UTF-8" standalone="no"?>

Building an XML Document: I'm doing it wrong

I'm trying to build an XML representation of some data. I've followed other examples, but I can't get it working. I've commented code down to this basic bit, and still nothing. This code compiles and runs OK, but the resulting output is empty. A call to dDoc.getDocumentElement() returns null. What am I doing wrong?
Please help me, Stack Overflow. You're my only hope.
DocumentBuilderFactory dFactory = DocumentBuilderFactory.newInstance();
dFactory.setValidating( false );
DocumentBuilder dBuilder = dFactory.newDocumentBuilder();
Document dDoc = dBuilder.newDocument();
// The root document element.
Element pageDataElement = dDoc.createElement("page-data");
pageDataElement.appendChild(dDoc.createTextNode("Example Text."));
dDoc.appendChild(pageDataElement);
log.debug(dDoc.getTextContent());
The following runs ok. You just need to call dDoc.getDocumentElement().getTextContent() instead of dDoc.getTextContent().
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
public class Demo {
public static void main(String[] args) throws Exception {
DocumentBuilderFactory dFactory = DocumentBuilderFactory.newInstance();
dFactory.setValidating( false );
DocumentBuilder dBuilder = dFactory.newDocumentBuilder();
Document dDoc = dBuilder.newDocument();
// The root document element.
Element pageDataElement = dDoc.createElement("page-data");
pageDataElement.appendChild(dDoc.createTextNode("Example Text."));
dDoc.appendChild(pageDataElement);
System.out.println(dDoc.getDocumentElement().getTextContent());
}
}
Will give the output:
Example Text.
You also can use http://xom.nu/
Xom has better API, small and very fast.

Categories