I have an xml file as:
<db>
<employees name="aaa">
<employee id="111">
<firstName>Rakesh</firstName>
<lastName>Mishra</lastName>
<location>Bangalore</location>
</employee>
<employee id="112">
<firstName>John</firstName>
<lastName>Davis</lastName>
<location>Chennai</location>
</employee>
<employee id="113">
<firstName>Rajesh</firstName>
<lastName>Sharma</lastName>
<location>Pune</location>
</employee>
</employees>
<employees name="bbb">
<employee id="222">
<firstName>a</firstName>
<lastName>a</lastName>
<location>a</location>
</employee>
<employee id="223">
<firstName>s</firstName>
<lastName>s</lastName>
<location>s</location>
</employee>
<employee id="224">
<firstName>d</firstName>
<lastName>d</lastName>
<location>d</location>
</employee>
</employees>
</db>
Is there any way where i can parse only first section of employees i.e data inside <employees name="aaa"> and </employees>
My java code is as follows:
public static void main(String args[]) {
try {
File stocks = new File("C:\\employee.xml");
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
Document doc = dBuilder.parse(stocks);
doc.getDocumentElement().normalize();
deList nodes = doc.getElementsByTagName("employee");
for (int i = 0; i < nodes.getLength(); i++) {
Node node = nodes.item(i);
if (node.getNodeType() == Node.ELEMENT_NODE) {
Element element = (Element) node;
System.out.println("\nStock firstName: " + getValue("firstName", element));
}
}
} catch (Exception ex) {
ex.printStackTrace();
}
}
private static String getValue(String tag, Element element) {
NodeList nodes = element.getElementsByTagName(tag).item(0).getChildNodes();
Node node = (Node) nodes.item(0);
return node.getNodeValue();
}
In this code i am not able to tag as
deList nodes = doc.getElementsByTagName("employee name="aaa"");
I even created string of this enitre name and passed but still no solutions.
Can anyone help me out in this.
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathFactory;
//your code
XPath xPath = XPathFactory.newInstance().newXPath();
String expression = "db/employees[#name='aaa']/employee";
NodeList nodeList =(NodeList)xPath.compile(expression).evaluate(xmlDocument,XPathConstants.NODESET);
for (int i = 0; i < nodeList.getLength(); i++) {
System.out.println(nodeList.item(i).getFirstChild().getNodeValue());
}
You can use XPath expressions.
public static void main(String[] args) {
DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = null;
try {
File stocks = new File("D:\\EmpDetails.xml");
builder = builderFactory.newDocumentBuilder();
Document document = builder.parse(stocks);
XPath xPath = XPathFactory.newInstance().newXPath();
String expression = "//employees[#name='aaa']/employee/firstName";
NodeList nodeList = (NodeList) xPath.compile(expression).evaluate(document, XPathConstants.NODESET);
//System.out.println("length is " + nodeList.getLength());
for (int i = 0; i < nodeList.getLength(); i++) {
System.out.println(nodeList.item(i).getFirstChild().getNodeValue());
}
} catch (SAXException ex) {
Logger.getLogger(ReadXML.class.getName()).log(Level.SEVERE, null, ex);
} catch (IOException ex) {
Logger.getLogger(ReadXML.class.getName()).log(Level.SEVERE, null, ex);
} catch (XPathExpressionException ex) {
Logger.getLogger(ReadXML.class.getName()).log(Level.SEVERE, null, ex);
} catch (ParserConfigurationException e) {
e.printStackTrace();
}
}
Related
class HtmlTagmodifier {
public String htmlFileWriter(String cfile, String Listname, String Nodename, String nodevalue) {
try {
File fhtmlFile = new File(cfile);
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
Document doc = dBuilder.parse(fhtmlFile);
doc.getDocumentElement().normalize();
NodeList nList = doc.getElementsByTagName(Listname);
for (int temp = 0; temp < nList.getLength(); temp++) {
Node nNode = nList.item(temp);
if (nNode.getNodeType() == Node.ELEMENT_NODE) {
Element eElement = (Element) nNode;
eElement.getElementsByTagName(Nodename).item(0).setTextContent(nodevalue);
}
}
Source source = new DOMSource(doc);
Result htmlresult = new StreamResult(fhtmlFile);
Transformer xformer = TransformerFactory.newInstance().newTransformer();
xformer.transform(source, htmlresult);
result2 = "Success";
} catch (Exception e) {
e.printStackTrace();
log.error("Error in html file writing " + e.toString());
JOptionPane.showMessageDialog(null, "Error in html file writing " + e.toString());
result2 = "Failed";
}
return result2;
}
public static void main(String[] args) {
HtmlTagmodifier.htmlfilewriter("test.html", "details", "customername", "customernamexxxxxx");
}
}
Output:
when i use this method to modify the tag values of html,tag name is changed successfully but meta data tag is added again in the html
please give me suggestion.
here's my code :
void validate(String fileLocation){
try{
DocumentBuilderFactory factory= DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document document = builder.parse(new File(fileLocation));
String[] pageContent=new String[100];
for (int i = 0; i < pageContent.length; i++) {
String currentPageContent= document.getElementsByTagName("?PG").item(i).getTextContent();
System.out.println("the Current Page content is "+currentPageContent);
pageContent[i]=currentPageContent;
}
}catch(Exception e){
e.printStackTrace();
}
}
i have several tags as < ?PG 1 ?> , < ?PG 2 ?>,< ?PG 3 ?> denoting page numbers how can i get get the data from page tag.
You can use recursion to go over the your xml without messy nested for loops.
You can compare the Node type to be PROCESSING_INSTRUCTION_NODE and extract its contents.
Example xml:
<?xml version="1.0" encoding="UTF-8" ?>
<test>
<ID>Test1</ID>
<TestType name="abc">
<AddressRange start="0x00000000" end="0x0018ffff" />
</TestType >
<TestType name="RAM">
<AddressRange start="0x00400000" end="0x00407fff" />
</TestType >
<?PITarget PIContent?>
<?PISource PISome?>
</test>
Code:
public static void main(String[] args) throws ParserConfigurationException,
SAXException, IOException {
FileInputStream path = new FileInputStream("text.xml");
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document document = builder.parse(path);
System.out.println();
traverse(document.getDocumentElement());
}
public static void traverse(Node node) {
NodeList list = node.getChildNodes();
for (int i = 0; i < list.getLength(); i++) {
Node currentNode = list.item(i);
traverse(currentNode);
}
if (node.getNodeType() == Node.PROCESSING_INSTRUCTION_NODE) {
System.out.println("This -> " + node.getTextContent());
}
}
Gives,
This -> PIContent
This -> PISome
If you want to read Processing Instructions in your code than you should do something like this:
NodeList currentPageContent= document.getChildNodes();
for (int i = 0; i < currentPageContent.getLength(); i++) {
Node node = currentPageContent.item(i);
if(node.getNodeType()==Node.PROCESSING_INSTRUCTION_NODE)
System.out.println("the Current Page content is "+ node.getNodeType()+ " : " + node.getNodeName() + " : " + node.getTextContent());
}
Hope this helps.
Processing instructions are exposed in the DOM(Document Object Model) as Node.PROCESSING_INSTRUCTION_NODE.
I have xml file
<A>
<A1>
<A2>Hi</A2>
</A1>
<A>
<B>
<B1></B1>
<B2>100</B2>
</B>
<A>
<A1>
<A2>Hello</A2>
</A1>
<A>
<B>
<B1>1000</B1>
<B2></B2>
</B>
likewise this goes more than 10 blocks. Now my java code able to read one by one that is first reads all after that reads tag.
Code:
public class XMLParse {
static Document doc;
public static void main(String argv[]) {
try {
File file = new File("/home/dev042/Desktop/xxx.xml");
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
doc = db.parse(file);
doc.getDocumentElement().normalize();
System.out.println("Root element " + doc.getDocumentElement().getNodeName());
NodeList nodeLst = doc.getElementsByTagName("A");
System.out.println("Information of all Balence Sheet");
int count = nodeLst.getLength();
String name;
for (int s = 0; s < nodeLst.getLength(); s++) {
Node fstNode = nodeLst.item(s);
if (fstNode.getNodeType() == Node.ELEMENT_NODE) {
Element fstElmnt = (Element) fstNode;
NodeList fstNmElmntLst = fstElmnt.getElementsByTagName("A1");
for(int i =0; i < fstNmElmntLst.getLength(); i++ )
{
Node lst = fstNmElmntLst.item(i);
if(lst.getNodeType() == Node.ELEMENT_NODE)
{
Element fsttravel = (Element) lst;
NodeList secNmElt = fsttravel.getElementsByTagName("*");
name = secNmElt.item(0).getTextContent();
System.out.println("Name : " + name);
}
}
}
}
}
catch (Exception e) {
e.printStackTrace();
}
String amt;
double amount;
NodeList nodeLst = doc.getElementsByTagName("B");
int coun = nodeLst.getLength();
for (int s = 0; s < nodeLst.getLength(); s++) {
Node secNode = nodeLst.item(s);
if (secNode.getNodeType() == Node.ELEMENT_NODE) {
try
{
Element amtval = (Element) secNode;
NodeList secval = amtval.getElementsByTagName("B1");
amt = secval.item(0).getTextContent();
//amount = Double.parseDouble(amt);
System.out.println("SubAmt :" + amt);
NodeList lstNmElmntLst = amtval.getElementsByTagName("B2");
amt = lstNmElmntLst.item(0).getTextContent();
System.out.println("MainAmt : " +amt);
}
catch(Exception ex){
ex.printStackTrace();
}
}
}
}
}
current output:
Hi
Hello
100
1000
I want to read the tags alternatively. then only i can able map the values. How can i read these tags alternatively. output should be like this
Hi 100
Hello 1000
Kindly help me out of it.
Thanks in advance..
I think you need to filter only tags so that your parser will fetch only tags.For this you can use XPath.This is an examples here:
http://www.roseindia.net/tutorials/xPath/java-xpath.shtml
Hi Everybody,
I am new to Android. I am using DOM parsing for reading xml string value. For that, I used following code, that code will work up to getting root element value after that it is giving exception please solve this problem,
Advance Thanks,
Xml Code:
<?xml version='1.0' encoding='UTF-8' standalone='yes' ?>
<ChangePassword>
<Oldpassword>23545565635354</Oldpassword>
<Newpassword>addsffggfdsfdsfdfs </Newpassword>
</ChangePassword>
java code:
File file = new File(getFilesDir().getAbsolutePath()+ File.separator + "test.xml"); DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Document doc = db.parse(file);
doc.getDocumentElement().normalize();
System.out.println("Root element " + doc.getDocumentElement().getNodeName());
NodeList nodeLst = doc.getElementsByTagName("ChangePassword");
System.out.println("Information of all entries");
for (int s = 0; s < nodeLst.getLength(); s++) {
Node fstNode = nodeLst.item(s);
if (fstNode.getNodeType() == Node.ELEMENT_NODE)
{
Element fstElmnt = (Element) fstNode;
// Firstname
NodeList fstNmElmntLst = ((Document) fstElmnt).getElementsByTagName("Oldpassword");
Element fstNmElmnt = (Element) fstNmElmntLst.item(0);
NodeList fstNm = ((Node) fstNmElmnt).getChildNodes();
System.out.println("Old password : " + ((Node) fstNm.item(0)).getNodeValue());
// Lastname
NodeList lstNmElmntLst = ((Document) fstElmnt).getElementsByTagName("Newpassword");
Element lstNmElmnt = (Element) lstNmElmntLst.item(0);
NodeList lstNm = ((Node) lstNmElmnt).getChildNodes();
System.out.println("Old password : " + ((Node) lstNm.item(0)).getNodeValue());
// Address
NodeList addrNmElmntLst = ((Document) fstElmnt).getElementsByTagName("Newpassword");
Element addrNmElmnt = (Element) addrNmElmntLst.item(0);
NodeList addrNm = ((Node) addrNmElmnt).getChildNodes();
System.out.println("Address : " + ((Node) addrNm.item(0)).getNodeValue());
}
}
} catch (Exception e) {
Log.e("Exception",e.toString());
//e.printStackTrace();
}
Wow. The DOM Parser code is pretty ugly. Please just try Simple XML instead. Look at what your code could be like:
#Root(name = "ChangePassword")
public class PasswordChange {
#Element(name = "Oldpassword")
public String oldPassword;
#Element(name = "Newpassword")
public String newPassword;
}
And that is much nicer. And then you can just say:
Serializer serial = new Persister();
PasswordChange pc = serial.read(PasswordChange.class, streamOrFileWithXML);
And that is all that there is to it. Though if you want to see how to include it in Android have a look at my blog post.
Document doc = db.parse(in);
Element docElem = doc.getDocumentElement();
NodeList nl = docElem.getElementsByTagName("Oldpassword");
try that...
update
maybe it would be helpful if you take a look here: http://www.w3schools.com/xml/default.asp
the following code is working, is just tested.
import java.io.File;
import java.io.IOException;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
public class testxml {
private String filepath = "src/xml.xml";
public void parse() {
File file = new File(filepath);
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db;
try {
db = dbf.newDocumentBuilder();
Document doc = db.parse(file);
Element docElem = doc.getDocumentElement();
NodeList nl1 = docElem.getElementsByTagName("Oldpassword");
for(int i = 0; i < nl1.getLength(); i++) {
Element entry = (Element)nl1.item(i);
System.out.println(entry.getFirstChild().getNodeValue());
}
NodeList nl2 = docElem.getElementsByTagName("Newpassword");
for(int i = 0; i < nl2.getLength(); i++) {
Element entry = (Element)nl2.item(i);
System.out.println(entry.getFirstChild().getNodeValue());
}
} catch (ParserConfigurationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SAXException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static void main(String args[]) {
testxml x = new testxml();
x.parse();
}
}
Try changing this line
NodeList nodeLst = doc.getElementsByTagName("ChangePassword");
To this
NodeList nodeLst = doc.getDocumentElement().getElementsByTagName("ChangePassword");
If not, show us your stack trace.
I have a simple XML file
<requirements>
<requirement>
<name> SwitchON</name>
<id>1</id>
<text>The Light shall turn on when the Switch is on.</text>
</requirement>
<requirement>
<name>SwitchOFF</name>
<id>2</id>
<text>The Light shall turn off when the Switch is off.</text>
</requirement>
<requirement>
<name>Lightbulb</name>
<id>3</id>
<text>The Light bulb shall be connected </text>
</requirement>
<requirement>
<name>Power</name>
<id>4</id>
<text>The Light shall have the power supply</text>
</requirement>
</requirements>
I am trying to show the information in this file in a table model.
I have a method (readFromXMl) that reads the XML file and returns a table model.
public static RequirementTable readFromXMl(String fileName) {
RequirementTable T = new RequirementTable();
Requirement R = new Requirement();
try {
DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder();
Document doc = docBuilder.parse(new File(fileName));
doc.getDocumentElement().normalize();
NodeList listOfRequirements = doc.getElementsByTagName("requirement");
int test = listOfRequirements.getLength();
System.out.println("Total no of people : " + test);
for (int i = 0; i < listOfRequirements.getLength(); i++) {
Node RequirementNode = listOfRequirements.item(i);
if (RequirementNode.getNodeType() == Node.ELEMENT_NODE) {
Element RequirementElement = (Element) RequirementNode;
NodeList IdList = RequirementElement.getElementsByTagName("id");
Element IdElement = (Element) IdList.item(0);
NodeList textIdList = IdElement.getChildNodes();
R.setId(Integer.parseInt(textIdList.item(0).getNodeValue()));
NodeList DescriptionList = RequirementElement.getElementsByTagName("text");
Element DescriptionElement = (Element) DescriptionList.item(0);
NodeList textDescriptionList = DescriptionElement.getChildNodes();
R.setText(textDescriptionList.item(0).toString());
NodeList NameList = RequirementElement.getElementsByTagName("name");
Element NameElement = (Element) NameList;
NodeList textNameList = NameElement.getChildNodes();
if (textNameList.item(0).toString().equals("SwitchON")) {
T.addRequirement((SwitchOnReq)R);
} else if (textNameList.item(0).toString().equals("SwitchOFF")) {
T.addRequirement((SwitchOFFReq)R);
} else if (textNameList.item(0).toString().equals("LightBulb")) {
T.addRequirement((BulbRequirement)R);
} else if (textNameList.item(0).toString().equals("Power")) {
T.addRequirement((PowerRequirement)R);
}
}
}
} catch (SAXParseException err) {
System.out.println("** Parsing error" + ", line " + err.getLineNumber() + ", uri " + err.getSystemId());
System.out.println(" " + err.getMessage());
} catch (SAXException e) {
Exception x = e.getException();
((x == null) ? e : x).printStackTrace();
} catch (Throwable t) {
t.printStackTrace();
}
return T;
}
However in this line I am getting an error which says the the pointer is null
Element IdElement = (Element) IdList.item(0); IdElement is null!!
Instead of all the looping and other xml ugliness, let me suggest a little helper method:
private static String getNodeValue(Node n, String path)
throws XPathExpressionException {
XPath xpath = XPathFactory.newInstance().newXPath();
return (String) xpath.evaluate(path, n, XPathConstants.STRING);
}
Use like this:
for (int i = 0; i < listOfRequirements.getLength(); i++) {
Node RequirementNode = listOfRequirements.item(i);
System.out.println("name:" + getNodeValue(RequirementNode, "name"));
System.out.println("id:" + getNodeValue(RequirementNode, "id"));
System.out.println("text:" + getNodeValue(RequirementNode, "text"));
...
to get all the values and set your requirements.