I'm new to Java. I saw many example about reading XML and when I tried to copy to my code I got an error that getTagValue is undefined.
I'm using Eclipse, JRE 1.6.
As well as I understand that method (getTagValue) is exist?
This is the errors:
Exception in thread "main" java.lang.Error: Unresolved compilation problems:
The method getTagValue(String, Element) is undefined for the type WriteXMLFile
The method getTagValue(String, Element) is undefined for the type WriteXMLFile
The method getTagValue(String, Element) is undefined for the type WriteXMLFile
The method getTagValue(String, Element) is undefined for the type WriteXMLFile
this the code:
import java.io.File;
import java.io.ObjectInputStream.GetField;
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;
import org.w3c.dom.NodeList;
import org.w3c.dom.Node;
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("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();
}
///// read
try {
File fXmlFile = new File("c:\\file.xml");
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
Document doc = dBuilder.parse(fXmlFile);
doc.getDocumentElement().normalize();
System.out.println("Root element :" + doc.getDocumentElement().getNodeName());
NodeList nList = doc.getElementsByTagName("staff");
System.out.println("-----------------------");
for (int temp = 0; temp < nList.getLength(); temp++) {
Node nNode = nList.item(temp);
if (nNode.getNodeType() == Node.ELEMENT_NODE) {
Element eElement = (Element) nNode;
System.out.println("First Name : " + getTagValue("firstname", eElement));
System.out.println("Last Name : " + getTagValue("lastname", eElement));
System.out.println("Nick Name : " + getTagValue("nickname", eElement));
System.out.println("Salary : " + getTagValue("salary", eElement));
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
This method needs to be included in your class file somewhere
private String getTagValue(String sTag, Element eElement) {
NodeList nlList = eElement.getElementsByTagName(sTag).item(0)
.getChildNodes();
Node nValue = (Node) nlList.item(0);
return nValue.getNodeValue();
}
Related
I want to get the value of the middle name from the below XML in JAVA.
<employee>
<emp1 name='firstName'>FNAme</emp1>
<emp1 name='middleName'>MNAme</emp1>
<emp1 name='LastName'>LNAme</emp1>
</employee>
this work for me pretty well:
java code
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.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
public class main
{
public static void main(String[] args) {
try {
File file = new File(".idea/company.xml");
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Document document = db.parse(file);
document.getDocumentElement().normalize();
System.out.println("Root Element :" + document.getDocumentElement().getNodeName());
NodeList nList = document.getElementsByTagName("employee");
System.out.println("----------------------------");
for (int temp = 0; temp < nList.getLength(); temp++) {
Node nNode = nList.item(temp);
System.out.println("\nCurrent Element :" + nNode.getNodeName());
if (nNode.getNodeType() == Node.ELEMENT_NODE) {
Element eElement = (Element) nNode;
System.out.println("First Name : " + eElement.getElementsByTagName("firstName").item(0).getTextContent());
System.out.println("Middle Name : " + eElement.getElementsByTagName("middleName").item(0).getTextContent());
System.out.println("Last Name : " + eElement.getElementsByTagName("lastName").item(0).getTextContent());
}
}
}
catch(IOException | ParserConfigurationException | SAXException e) {
System.out.println(e);
}
the xml look like this:
<?xml version="1.0"?>
<company>
<employee>
<firstName>FNAme</firstName>
<middleName>MNAme</middleName>
<lastName>LNAme</lastName>
</employee>
</company>
If I switch it to xml it works fine but to kml nothing. thought it was basically the same thing,probably missing something silly, or messed it up completly sorry for inconvience but help is much appreciated. basically just trying to read a kml file data on java.
package mysqlcon;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.DocumentBuilder;
import org.w3c.dom.Document;
import org.w3c.dom.NodeList;
import org.w3c.dom.Node;
import org.w3c.dom.Element;
import java.io.File;
public class ReadXMLFile {
public static void main(String argv[]) {
try {
File fXmlFile = new File("C:/Users/D/Desktop/mysql/mappedv.kml");
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
Document doc = dBuilder.parse(fXmlFile);
doc.getDocumentElement().normalize();
System.out.println("Root element :" + doc.getDocumentElement().getNodeName());
NodeList nList = doc.getElementsByTagName("mappedv");
System.out.println("----------------------------");
for (int temp = 0; temp < nList.getLength(); temp++) {
Node nNode = nList.item(temp);
System.out.println("\nCurrent Element :" + nNode.getNodeName());
if (nNode.getNodeType() == Node.ELEMENT_NODE) {
Element eElement = (Element) nNode;
System.out.println("coordinates : " + eElement.getElementsByTagName("coordinates").item(0).getTextContent());
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
<table name="categoryConfigTable">
<row>
<field name="mediaConfigId">0</field>
<field name="startDate">2005-01-01</field>
<field name="endDate">2025-12-31</field>
<field name="class">all</field>
<field name="CID">10</field>
<field name="sequenceNum">1</field>
<field name="parentCID">NULL</field>
</row>
</table>
This is part of my XML file, I want to retrieve CID values having parentCID as NULL
Part of my JAVA code is
`
public static void main(String[] args) {
try {
File fXmlFile = new File("/home/media.xml");
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
Document doc = dBuilder.parse(fXmlFile);
doc.getDocumentElement().normalize();
System.out.println("Root element :" + doc.getDocumentElement().getNodeName());
NodeList nlist = doc.getElementsByTagName("field");
int len = nlist.getLength();
for (int i = 0; i < len; i++) {
Node node = nlist.item(i);
if (node.getNodeType() == Node.ELEMENT_NODE) {
Element e = (Element)node;
String attrVal = e.getAttribute("name");
try {
if(attrVal.equalsIgnoreCase("parentCID") && e.getTextContent().equals("NULL"))
{
System.out.println("root element" +e.getTextContent());
}
}
catch (IOException ie) {
//exception handling left as an exercise for the reader
}
}
}}catch (Exception e) {
e.printStackTrace();
}
}`
From this I get all parentCID having value as null but I want to go to CID how this can be done?
you can get it like this
import java.io.File;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
public class ReadXMLFile {
public static void main(String argv[]) {
try {
File fXmlFile = new File("src/test.xml");
DocumentBuilderFactory dbFactory = DocumentBuilderFactory
.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
Document doc = dBuilder.parse(fXmlFile);
doc.getDocumentElement().normalize();
System.out.println("Root element :"
+ doc.getDocumentElement().getNodeName());
NodeList nList = doc.getElementsByTagName("row");
System.out.println("----------------------------");
for (int temp = 0; temp < nList.getLength(); temp++) {
Node nNode = nList.item(temp);
//System.out.println("\nCurrent Element :" + nNode.getNodeName());
if (nNode.getNodeType() == Node.ELEMENT_NODE) {
Element eElement = (Element) nNode;
NodeList nList2 = eElement.getElementsByTagName("field");
String cidvalue=null;
for (int temp1 = 0; temp1 < nList2.getLength(); temp1++) {
Node nNode1 = nList2.item(temp1);
//System.out.println("\nCurrent Element Internal :"+ nNode1.getNodeName());
if (nNode1.getNodeType() == Node.ELEMENT_NODE) {
Element eElement1 = (Element) nNode1;
if(eElement1.getAttribute("name").equalsIgnoreCase("CID"))
{
cidvalue=eElement1.getTextContent();
}
if(eElement1.getAttribute("name").equalsIgnoreCase("parentCID") && (eElement1.getTextContent().equalsIgnoreCase("NULL")))
{
// System.out.println(eElement1.getTextContent());
System.out.println("row["+temp+"] where parentCID is NULL and corresponding CID value :: "+cidvalue);
cidvalue=null;
}
}
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
I have an xml file in the following pattern which contains a few Complex Empty Elements(elements with no content, only attributes).
<items>
<item id="0" name="a" />
<item id="1" name="b" />
</items>
I'm at lose to parse the attributes from them. This is what I have done so far :
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document document = builder.parse(inputStream);
Element itemsElement = document.getDocumentElement();
if (itemsElement.getTagName().equals(TAG_ITEMS)) {
NodeList nodeList = itemsElement.getChildNodes();
for (int i = 0; i < nodeList.getLength(); i++) {
// process each item node
Node node = nodeList.item(i);
if (node.getNodeType() == Node.TEXT_NODE) { // Is this the right way?
Text text = (Text) node;
// Do stuff with attributes
}
}
}
I cannot cast these Text nodes to Element nodes and get attributes, I cannot get attributes from node using getAttributes - NPE at NamedNodeMap attributes.getLength(), I cannot cast it to Text and get attributes. How can I parse the attributes?
You are not interested in the text context of the nodes inside of items but in the attributes of the nodes item. you could proceed as follow:
//process each item node
Node node = nodeList.item(i);
if (node.getNodeName().equals("item")) {
NamedNodeMap attributes = node.getAttributes();
System.out.printf("id=%s, name=%s%n",
attributes.getNamedItem("id").getTextContent(),
attributes.getNamedItem("name").getTextContent());
}
This would print:
id=0, name=a
id=1, name=b
Assuming you want to get the indiviudal attributes of the nodes you need to one of two things (or both depending on your needs)...
You need to test if the current node is an ELEMENT_NODE or if the current node's name is equal to item (assuming all the node names are the same), for example...
import java.io.InputStream;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.w3c.dom.Text;
public class Test {
public static final String TAG_ITEMS = "items";
public static void main(String[] args) {
try (InputStream is = Test.class.getResourceAsStream("/Test.xml")) {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document document = builder.parse(is);
Element itemsElement = document.getDocumentElement();
if (itemsElement.getTagName().equals(TAG_ITEMS)) {
NodeList nodeList = itemsElement.getChildNodes();
for (int i = 0; i < nodeList.getLength(); i++) {
Node node = nodeList.item(i);
if (node.getNodeType() == Node.ELEMENT_NODE) {
NamedNodeMap attributes = node.getAttributes();
Node idAtt = attributes.getNamedItem("id");
Node nameAtt = attributes.getNamedItem("name");
System.out.println("id = " + idAtt.getNodeValue());
System.out.println("name = " + nameAtt.getNodeValue());
}
}
}
} catch (Exception exp) {
exp.printStackTrace();
}
}
}
Which will output...
id = 0
name = a
id = 1
name = b
All of this could be greatly reduced by using XPath, for example, if all the item nodes are the same name, then you could just use
/items/item
As the query. If the node names are different, but the attributes are the same, then you could use
/items/*[#id]
which will list all the nodes under items which has an id attribute, or
/items/*[#name]
which will list all the nodes under items which has an name attribute...
import java.io.InputStream;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpression;
import javax.xml.xpath.XPathFactory;
import org.w3c.dom.Document;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
public class Test {
public static void main(String[] args) {
try (InputStream is = Test.class.getResourceAsStream("/Test.xml")) {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document document = builder.parse(is);
XPath xpath = XPathFactory.newInstance().newXPath();
XPathExpression expression = xpath.compile("/items/item");
NodeList nodes = (NodeList) expression.evaluate(document, XPathConstants.NODESET);
process(nodes);
expression = xpath.compile("/items/*[#id]");
nodes = (NodeList) expression.evaluate(document, XPathConstants.NODESET);
process(nodes);
expression = xpath.compile("/items/*[#name]");
nodes = (NodeList) expression.evaluate(document, XPathConstants.NODESET);
process(nodes);
} catch (Exception exp) {
exp.printStackTrace();
}
}
protected static void process(NodeList nodes) {
for (int index = 0; index < nodes.getLength(); index++) {
Node item = nodes.item(index);
NamedNodeMap attributes = item.getAttributes();
Node idAtt = attributes.getNamedItem("id");
Node nameAtt = attributes.getNamedItem("name");
System.out.println("id = " + idAtt.getNodeValue() + "; name = " + nameAtt.getNodeValue());
}
}
}
I have a XML file with data that is used in both my C# and Java version of a library.
Ideally I want to embed this XML file in a package in that library.
I only need to access it from within my library, so I was wondering: is that possible?
In Java, you could include the XML file itself in the JAR file. You can then use something like this:
InputStream istream = getClass().getResourceAsStream("/resource/path/to/some.xml");
And parse your InputStream as normal.
The above getResourceAsStream() looks in the current classpath, which would include the contents of any JAR files.
book.xml
<book>
<person>
<first>Kiran</first>
<last>Pai</last>
<age>22</age>
</person>
<person>
<first>Bill</first>
<last>Gates</last>
<age>46</age>
</person>
<person>
<first>Steve</first>
<last>Jobs</last>
<age>40</age>
</person>
<person>
<first>kunal</first>
<last>kumar</last>
<age>25</age>
</person>
</book>
create a xml file book.xml
made a jar file book.xml.jar and
palce it in war/web-inf/lib folder of your project..
then it will work..
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import javax.servlet.http.*;
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.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
import org.xml.sax.SAXParseException;
#SuppressWarnings("serial")
public class XMLParser extends HttpServlet {
InputStream istream =getClass().getResourceAsStream("/book.xml");
public void doGet(HttpServletRequest req, HttpServletResponse resp)throws IOException
{
DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder docBuilder = null;
try {
docBuilder = docBuilderFactory.newDocumentBuilder();
} catch (ParserConfigurationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Document doc = null;
try {
doc = docBuilder.parse (istream);
} catch (SAXException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// normalize text representation
doc.getDocumentElement ().normalize ();
System.out.println ("Root element of the doc is " +
doc.getDocumentElement().getNodeName());
NodeList listOfPersons = doc.getElementsByTagName("person");
int totalPersons = listOfPersons.getLength();
System.out.println("Total no of people : " + totalPersons);
for(int s=0; s<listOfPersons.getLength() ; s++){
Node firstPersonNode = listOfPersons.item(s);
if(firstPersonNode.getNodeType() == Node.ELEMENT_NODE){
Element firstPersonElement = (Element)firstPersonNode;
//-------
NodeList firstNameList = firstPersonElement.getElementsByTagName("first");
Element firstNameElement = (Element)firstNameList.item(0);
NodeList textFNList = firstNameElement.getChildNodes();
System.out.println("First Name : " +
((Node)textFNList.item(0)).getNodeValue().trim());
//-------
NodeList lastNameList = firstPersonElement.getElementsByTagName("last");
Element lastNameElement = (Element)lastNameList.item(0);
NodeList textLNList = lastNameElement.getChildNodes();
System.out.println("Last Name : " +
((Node)textLNList.item(0)).getNodeValue().trim());
//----
NodeList ageList = firstPersonElement.getElementsByTagName("age");
Element ageElement = (Element)ageList.item(0);
NodeList textAgeList = ageElement.getChildNodes();
System.out.println("Age : " +
((Node)textAgeList.item(0)).getNodeValue().trim());
//------
}//end of if clause
}//end of for loop with s var
//System.exit (0);
}//end of main
}