Java Print XML to console [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 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>

Related

Splitting XML String by tags in java [duplicate]

This question already has answers here:
Why is it such a bad idea to parse XML with regex? [closed]
(3 answers)
Closed 6 years ago.
How can I split an xml-string into different xml-strings by tag?
Suppose I have the following XML. How can I have a xml-string with
tag1 and its values,
tag2 and its values and,
tag3 with its values.
<?xml version="1.0"?>
<Tag0>
<Tag1> //Other tags and values for tag1 </Tag1>
<Tag2> </Tag2>
<Tag3> </Tag3>
</Tag0>
I'm splitting the XML because when I create the XSD for the xml-strings it creating just XSD for just the tag1 because rest of them have the same namespace as tag1.
After you parse the XML you can call the method getElementsByTagName this will return a NodeList, and just instantiate a Node object for each element from the NodeList.
Use a SAXParser to parse the xml to Java object first. You can then get anything using it.
Here is the code to do the splitting in XPath and vtd-xml.
import com.ximpleware.*;
import java.io.*;
public class splitXML {
public static void main(String[] args) throws VTDException, IOException {
VTDGen vg = new VTDGen();
if (!vg.parseFile("d:\\xml\\input.xml", false)){
System.out.println("error");
return;
}
VTDNav vn = vg.getNav();
AutoPilot ap = new AutoPilot(vn);
ap.selectXPath("/tag0/*");
int i=0,n=0;
FileOutputStream fos =null;
while((i=ap.evalXPath())!=-1){
fos = new FileOutputStream("d:\\xml\\output"+(++n)+".xml");
long l = vn.getElementFragment();
fos.write(vn.getXML().getBytes(), (int)l, (int)(l>>32));
fos.close();
}
}
}

How to get specified roots from xml? [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 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);

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

read multiple xml files from the folder and write one output text file(comma separated)

I need to read all the input xml files from the folder and write one output text file, comma separated. I have the following code program read one file, can someone please help me to modify it and read all the files from the c:/java/ folder. thanks
import java.io.IOException;
import org.w3c.dom.*;
import org.xml.sax.SAXException;
import javax.xml.parsers.*;
import javax.xml.xpath.*;
public class XPathExample {
public static void main(String[] args) throws ParserConfigurationException,
SAXException, IOException, XPathExpressionException {
DocumentBuilderFactory domFactory = DocumentBuilderFactory
.newInstance();
domFactory.setNamespaceAware(true);
DocumentBuilder builder = domFactory.newDocumentBuilder();
Document doc = builder.parse("c:/java/test.xml");
XPathFactory factory = XPathFactory.newInstance();
XPath xpath = factory.newXPath();
XPathExpression expr = xpath.compile("//FORM[#name='F00001'] /*/text()");
Object result = expr.evaluate(doc, XPathConstants.NODESET);
NodeList nodes = (NodeList) result;
for (int i = 0; i < nodes.getLength(); i++) {
System.out.println(nodes.item(i).getNodeValue());
}
}
}
Use this to iterate all files in your directory:
Read all files in a folder
Output (file in dir) use as input here
Document doc = builder.parse("<dir file>");
If file is not xml, it either return null or exceprion is raised (I dont know currently). Eitherway, you will have to solve this.
To get all the files in the directory C:\java you can use the code:
for (File file : new File("C:\\java").listFiles())
{
Document doc = builder.parse(file.getAbsolutePath());
...
}
You can play about with where you add the rest of your code around this loop. You should also add some basic checks that what you're trying to parse is indeed XML too.

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

Categories