I have a series of XML files I am looking through and grabbing a specific element from.
<key>A</key>
I'm using this snippet of code to grab the XML element, but it returns null instead of the element I am looking for. I am not able to change the XML files.
File key = new File(filePath);
PrintWriter keyWriter = new PrintWriter(key);
File xmlFile = new File(configPath);
DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
Document document = documentBuilder.parse(xmlFile);
NodeList nodes = document.getElementsByTagName("key");
Element keyValue = (Element) nodes.item(0);
keyWriter.println(keyValue);
keyWriter.close();
}
I've tried using the document method as well as the apache xmlconfiguration and getElementbyId but all have returned null so far.
I noticed in your code that your passing the element object to the writer's println function as in:
keyWriter.println(keyValue);
This will print a null value in the file. Try replacing it with:
keyWriter.println(keyValue.getTextContent());
Related
I have this XML code:
<?xml version="1.0" encoding="utf-8"?>
<string xmlns="https://www.cvlkra.com/">tTKyEndh0iBqnZdjpUntEQ%3d%3d</string>
I want to get this: tTKyEndh0iBqnZdjpUntEQ%3d%3d for which I have tried the below code:
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder1 = factory.newDocumentBuilder();
Document document = builder1.parse(new InputSource(new StringReader(string)));
Element rootElement = document.getDocumentElement();
String nodeName = rootElement.getNodeName();
But i am not getting it. I am getting null value instead of tTKyEndh0iBqnZdjpUntEQ%3d%3d even when I have tried some other code also.
Try using getTextContent() instead getNodeValue() returns null because it has no values.
You should not use getNodeName() instead use rootElement.getNodeValue(). May be this helps.
I have the following XML document which I'm trying to get the inner text. I have tried numerous ways, using Xpath, DOM, SAX but no success.
This is my XML, I'm not sure if it's the XML structure which is causing a problem or my code.
<?xml version="1.0"?>
<ArrayOfPurchaseEntitites xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema">
<PurchaseEntitites>
<rInstalmentAmt>634.0</rInstalmentAmt>
<rAnnualRate>12.0</rAnnualRate>
<rInterestAmt>2670.0</rInterestAmt>
<dFirstInstalment>3/31/2016 12:00:00 AM</dFirstInstalment>
<dLastInstalment>8/31/2018 12:00:00 AM</dLastInstalment>
<rInsurancePremium>1350.0</rInsurancePremium>
<sResponseCode>00</sResponseCode>
</PurchaseEntitites>
</ArrayOfPurchaseEntitites>
InputStream stream = connect.getInputStream();
DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
documentBuilderFactory.setNamespaceAware(true);
DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
Document doc = documentBuilder.parse(stream);
doc.normalize();
System.out.println("===============================================================");
String g = doc.getDocumentElement().getTextContent();
System.out.println(g);
NodeList rootNodes = doc.getElementsByTagName("ArrayOfPurchaseEntitites");
Node rootnode =rootNodes.item(0);
Element rootElement = (Element) rootnode;
NodeList noteslist = rootElement.getElementsByTagName("PurchaseEntitites");
for(int i = 0; i < noteslist.getLength(); i++)
{
Node theNote = noteslist.item(i);
Element noteElement =(Element) theNote;
Node theExpiryDate = noteElement.getElementsByTagName("dLastInstalment").item(0);
Element dateElement = (Element) theExpiryDate;
System.out.println(dateElement.getTextContent());
}
stream.close();
I had a similar problem where I wanted to call getElementsByTagName for the first item in a NodeList. The trick - which you already utilize - is to cast the Node to Element. However, just to be sure, I suggest you add if (rootnode instanceof Element).
Assuming you use packages javax.xml.parsers and org.w3c.dom (no wild guess) your code works nicely when the xml is read from a file.
So if there still a problem with the code (it's been a while since this question was asked) I suggest you update the question with more info regarding connect.getInputStream();.
I have an XML as below
<accountProducts>
<accountProduct>...</accountProduct>
<accountProduct>...</accountProduct>
<accountProduct>...</accountProduct>
<accountProduct>...</accountProduct>
</accountProducts>
Now I want to extract each of the accountProduct block as string. So is there any XML parsing technique to do that or I need to do string manipulation.
Any help please.
Using the DOM as suggested above, you will need to parse your XML with a DocumentBuilder.
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
//if your document has namespaces, you can specify that in your builder.
DocumentBuilder db = dbf.newDocumentBuilder();
Using this object, you can call the parse() method.
Your XML input can be provided to a DOM parser as a file or as a stream.
As a file...
File f = new File("MyXmlFile.xml");
Document d = db.parse(f);
As a string...
String myXmlString = "...";
InputSource ss = new InputSource(new StringReader(myXmlString));
Document d = db.parse(ss);
Once you have a Document object, you can traverse the document with DOM functions or with XPATH. This example illustrates the DOM methods.
In your example, assuming that accountProduct nodes contain only text, the following should work.
NodeList nl = d.getElementsByTagName("accountProduct");
for(int i=0; i<nl.getLength(); i++) {
Element elem = (Element)nl.item(i);
System.out.println(elem.getTextContent());
}
If accountProduct contains mixed content (text and elements), you would need more code to extract what you need.
Use JAXP for this.
The Java API for XML Processing (JAXP) is for processing XML data using applications written in the Java programming language.
I've written a twitter desktop app that basically just lets me post tweets and pics... nothing fancy.
I've got everything working but this last part of persisting a config file (which is the following XML generated by my application.
<?xml version="1.0" encoding="UTF-8" standalone="no"?><Twitterer><config id="1"><accessToken>ENDLESS-STRING-OF-CHARACTERS</accessToken><accessTokenSecret>ANOTHER-ENDLESS-STRING-OF-CHARACTERS</accessTokenSecret></config></Twitterer>
What I need to do is just set the accessToken & accessTokenSecret variables. The filename is config.xml.
I've been looking at a lot of examples on the net, but can't seem to wrap my head around only getting two values from the file, which shouldn't need a loop.
This is as far as I've gotten on this last piece of my puzzle:
try {
File fXmlFile = new File(this.getFileName());
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
Document doc = dBuilder.parse(fXmlFile);
doc.getDocumentElement().normalize();
NodeList nList = doc.getElementsByTagName("config");
int numberOfConfigs = nList.getLength();
// GET THE TWO VARIABLES HERE
} catch (Exception e) {
}
If anyone can help me just read those two tags into their corresponding variables I would be quite appreciative. I can handle the rest of the Authorization after that.
What I need to do is just set the accessToken & accessTokenSecret variables
A simple code using getElementsByTagName() method
Element root = doc.getDocumentElement();
root.getElementsByTagName("accessToken").item(0).getTextContent()
root.getElementsByTagName("accessTokenSecret").item(0).getTextContent()
output:
ENDLESS-STRING-OF-CHARACTERS
ANOTHER-ENDLESS-STRING-OF-CHARACTERS
OR try as child node of config tag
Element root = doc.getDocumentElement();
NodeList configNodeList = root.getElementsByTagName("config");
NodeList nodeList = ((Node) configNodeList.item(0)).getChildNodes();
System.out.println(nodeList.item(0).getTextContent());
System.out.println(nodeList.item(1).getTextContent());
I am using XMLConfiguration to get DOM Document object from the configuration object as
given below:
XMLConfiguration config = new XMLConfiguration("xml file path");
Document document = config.getDocument();
But it is returning null document object .
Am I using right approach?
If you didn't get an exception thrown by new XMLConfiguration(), it means that configuration was loaded successfully.
I'm willing to bet that you concluded that it's a "null document object" because you tried to print the value of document and got something like:
[Document: null]
That doesn't mean a "null document".
You can use below approach also:
File xmlFile = new File("xml file path");
DocumentBuilderFactory documentFactory = DocumentBuilderFactory
.newInstance();
DocumentBuilder documentBuilder = documentFactory
.newDocumentBuilder();
Document doc = documentBuilder.parse(xmlFile);