XML gets all nodes with the same name
I have xml docs that looks like this:
<?xml version="1.0"?>
<root>
<success>true</success>
<note>
<note_id>32219</note_id>
<the_date>1336763490</the_date>
<member_id>108649</member_id>
<area>6</area>
<note>Note 123123123</note>
</note>
<note>
<note_id>33734</note_id>
<the_date>1339003652</the_date>
<member_id>108649</member_id>
<area>1</area>
<note>This is another note.</note>
</note>
<note>
<note_id>49617</note_id>
<the_date>1343050791</the_date>
<member_id>108649</member_id>
<area>1</area>
<note>this is a 3rd note.</note>
</note>
</root>
I would like to take this document and get all the tags <note>
and convert them to string, then pass them to my XML class and put the XML class in a list of arrays. I hope this makes sense. So, here is the method I am trying to use to get all the tags <note>
.
public ArrayList<XML> getNodes(String root, String name){
ArrayList<XML> elList = new ArrayList<>();
NodeList nodes = doc.getElementsByTagName(root);
for(int i = 0; i < nodes.getLength(); i++){
Element element = (Element)nodes.item(i);
NodeList nl = element.getElementsByTagName(name);
for(int c = 0; c < nl.getLength(); c++){
Element e = (Element)nl.item(c);
String xmlStr = this.nodeToString(e);
XML xml = new XML();
xml.parse(xmlStr);
elList.add(xml);
}
}
return elList;
}
private String nodeToString(Node node){
StringWriter sw = new StringWriter();
try{
Transformer t = TransformerFactory.newInstance().newTransformer();
t.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
t.transform(new DOMSource(node), new StreamResult(sw));
}catch(TransformerException te){
System.out.println("nodeToString Transformer Exception");
}
return sw.toString();
}
So my question is, how can I get each tag <note>
as a string? With the code I have, I now go back null
for String xmlStr = e.getNodeValue();
.
Edit
I edited my main code, this seems to work.
source to share
Updated after clarification
You can find all elements <note>
using XPath.
This will allow you to isolate each node simply. Then you can create a new document based on the found nodes and convert it to string
public class TestXML01 {
public static void main(String[] args) {
String xml = "<?xml version=\"1.0\"?>";
xml += "<root>";
xml += "<success>true</success>";
xml += "<note>";
xml += "<note_id>32219</note_id>";
xml += "<the_date>1336763490</the_date>";
xml += "<member_id>108649</member_id>";
xml += "<area>6</area>";
xml += "<note>Note 123123123</note>";
xml += "</note>";
xml += "<note>";
xml += "<note_id>33734</note_id>";
xml += "<the_date>1339003652</the_date>";
xml += "<member_id>108649</member_id>";
xml += "<area>1</area>";
xml += "<note>This is another note.</note>";
xml += "</note>";
xml += "<note>";
xml += "<note_id>49617</note_id>";
xml += "<the_date>1343050791</the_date>";
xml += "<member_id>108649</member_id>";
xml += "<area>1</area>";
xml += "<note>this is a 3rd note.</note>";
xml += "</note>";
xml += "</root>";
ByteArrayInputStream bais = null;
try {
bais = new ByteArrayInputStream(xml.getBytes());
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setNamespaceAware(false);
DocumentBuilder builder = factory.newDocumentBuilder();
Document xmlDoc = builder.parse(bais);
Node root = xmlDoc.getDocumentElement();
XPathFactory xFactory = XPathFactory.newInstance();
XPath xPath = xFactory.newXPath();
XPathExpression xExpress = xPath.compile("/root/note");
NodeList nodes = (NodeList) xExpress.evaluate(root, XPathConstants.NODESET);
System.out.println("Found " + nodes.getLength() + " note nodes");
for (int index = 0; index < nodes.getLength(); index++) {
Node node = nodes.item(index);
Document childDoc = builder.newDocument();
childDoc.adoptNode(node);
childDoc.appendChild(node);
System.out.println(toString(childDoc));
}
} catch (Exception exp) {
exp.printStackTrace();
} finally {
try {
bais.close();
} catch (Exception e) {
}
}
}
public static String toString(Document doc) {
String sValue = null;
ByteArrayOutputStream baos = null;
OutputStreamWriter osw = null;
try {
baos = new ByteArrayOutputStream();
osw = new OutputStreamWriter(baos);
Transformer tf = TransformerFactory.newInstance().newTransformer();
tf.setOutputProperty(OutputKeys.INDENT, "yes");
tf.setOutputProperty(OutputKeys.METHOD, "xml");
tf.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4");
DOMSource domSource = new DOMSource(doc);
StreamResult sr = new StreamResult(osw);
tf.transform(domSource, sr);
osw.flush();
baos.flush();
sValue = new String(baos.toByteArray());
} catch (Exception exp) {
exp.printStackTrace();
} finally {
try {
osw.close();
} catch (Exception exp) {
}
try {
baos.close();
} catch (Exception exp) {
}
}
return sValue;
}
}
Now this is outputting ...
Found 3 note nodes
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<note>
<note_id>32219</note_id>
<the_date>1336763490</the_date>
<member_id>108649</member_id>
<area>6</area>
<note>Note 123123123</note>
</note>
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<note>
<note_id>33734</note_id>
<the_date>1339003652</the_date>
<member_id>108649</member_id>
<area>1</area>
<note>This is another note.</note>
</note>
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<note>
<note_id>49617</note_id>
<the_date>1343050791</the_date>
<member_id>108649</member_id>
<area>1</area>
<note>this is a 3rd note.</note>
</note>
source to share
Using XPath, the following code:
public class NotesExtractor {
public static List< String > getTextOf( Document doc, String tagName )
throws Exception
{
List< String > notes = new ArrayList<>();
XPathFactory xPathFactory = XPathFactory.newInstance();
XPath xPath = xPathFactory.newXPath();
NodeList xText =
(NodeList)xPath.evaluate(
"//" + tagName + "/text()", doc, XPathConstants.NODESET );
for( int i = 0; i < xText.getLength(); ++i ) {
Text textElt = (Text)xText.item( i );
String noteTxt = textElt.getTextContent().trim();
if( ! noteTxt.isEmpty())
{
notes.add( noteTxt.trim());
}
}
return notes;
}
public static void main( String[] args ) throws Exception {
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
dbf.setIgnoringElementContentWhitespace( true );
DocumentBuilder db = dbf.newDocumentBuilder();
Document doc = db.parse( "Notes.xml" );
System.out.println( getTextOf( doc, "note" ));
}
outputs:
[Note 123123123, This is another note., this is a 3rd note.]
source to share