How to parse/process this XML (DOM or SAX)?
Hello all,
Here is a set of XML nodes that I need to process.
<message>
<text>
The meeting is scheduled <secure>at 1600hrs</secure> and the attendees will be VP engineering, VP finance, VP products.
</text>
</message>
In the above XML, when I use a DOM parser to get the text of the tag <text> I get all the characters till <secure>.. However, I do not get the text after the </secure> .
What am I missing? Isnt this XML valid? It sure does look a lot like an XHTML. In which case I suspect the XML is valid.
Please advise.
Thanks and Cheers
Gautham Kasinath
# 1
The <text> node contains two separate text-type nodes and one element-type node as follows:
1. "The meeting is scheduled"
2. <secure>at 1600hrs</secure>
3. "and the attendees will be VP engineering, VP finance, VP products."
If you want to concatenate all the text content inside the <text> node to one sentence, you could use this:Node text = <the node named "text">
String sentence = text.getTextContent();
The "sentence" variable stores the following string:The meeting is scheduled at 1600hrs and the attendees will be VP engineering, VP finance, VP products.
# 2
Hello
Try this
import java.io.File;
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.w3c.dom.NodeList;
import org.xml.sax.SAXException;
public class TestXMLReader {
public static void main(String[] args) {
try {
(new TestXMLReader()).readXML();
} catch (Exception e) {
e.printStackTrace();
}
}
XPath xpath = XPathFactory.newInstance().newXPath();
private void readXML() throws ParserConfigurationException, SAXException,
IOException, XPathExpressionException {
DocumentBuilder builder = DocumentBuilderFactory.newInstance()
.newDocumentBuilder();
Document document = builder.parse(new File(/*xml path*/));
String root = document.getDocumentElement().getNodeName();
Node rootNode = (Node) xpath.evaluate(root, document,
XPathConstants.NODE);
System.out.println("Root : " + rootNode.getNodeName());
String expression = "/message/text"; // or "//text";
Node childNode = (Node) xpath.evaluate(expression, document,
XPathConstants.NODE);
System.out.println("Node : " + childNode.getNodeName());
String expression2 = "//text/text()";
NodeList nameNodes = (NodeList) xpath.evaluate(expression2, document,
XPathConstants.NODESET);
for (int i = 0; i < nameNodes.getLength(); i++) {
System.out.println("Text : " + nameNodes.item(i).getTextContent());
}
}
}