how to read few points from xml using java - java

I'm new to XML and I want to append points from an XML file to a point container that I wrote.
this is the XML file:
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<container>
<point>
<X>56</X>
<Y>58</Y>
</point>
<point>
<X>59</X>
<Y>40</Y>
</point>
<point>
<X>70</X>
<Y>30</Y>
</point>
</container>
this is what I did:
private void OpenFile () throws ParserConfigurationException, SAXException, IOException {
JFileChooser of = new JFileChooser();
int option = of.showOpenDialog(of);
while (!of.getSelectedFile().getName().endsWith(".xml")) {
String error = "Error, Please select txt file";
JOptionPane.showMessageDialog(this, error, "Wrong type of file", JOptionPane.INFORMATION_MESSAGE);
of = new JFileChooser();
option = of.showOpenDialog(of);
}
if (option == JFileChooser.APPROVE_OPTION){
thisFile = new File(of.getSelectedFile().getPath());
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
Document doc = dBuilder.parse(thisFile);
doc.getDocumentElement().normalize();
NodeList nList = doc.getElementsByTagName("container");
Element line = (Element) nList.item(0);
for(int i =0 ; i < nList.getLength() ; i++) {
Element point = (Element) line.getElementsByTagName("point").item(i);
x = Integer.parseInt(point.getElementsByTagName("X").item(0).getTextContent());
y = Integer.parseInt(point.getElementsByTagName("Y").item(0).getTextContent());
drewPoints(x, y);
pc.add(new Point(x, y));
}
}
my problem that it loop one time.

nList contains the list of container nodes, and you have only one such element in the XML document. You need to get the point elements instead:
NodeList nList = doc.getElementsByTagName("container");
Element containerElement = (Element) nList.item(0);
NodeList pointNodes = containerElement.getElementsByTagName("point");
for(int i = 0; i < pointNodes.getLength(); i++) {
Element point = (Element) pointNodes..item(i);
...

"my problem that it loop one time."
-- this is due to their being only one <container> node which is being iterated over:
NodeList nList = doc.getElementsByTagName("container"); // nList.getLength() == 1 here
Element line = (Element) nList.item(0);
for(int i =0 ; i < nList.getLength() ; i++) { // looping from i = 0 to i = 1
To make it iterate over all the points, do something like:
NodeList nList = doc.getElementsByTagName("container");
Element container = (Element) nList.item(0);
NodeList pointsList = container.getElementsByTagName("point");
for (int i = 0; i < pointsList.getLength(); i++) {
Element point = (Element) pointsList.item(i);
x = Integer.parseInt(point.getElementsByTagName("X").item(0).getTextContent());
y = Integer.parseInt(point.getElementsByTagName("Y").item(0).getTextContent());
drewPoints(x, y);
pc.add(new Point(x, y));
}

The issue in your code is that your are terminating the loop using nList.getLength() instead of line.getLength().
for(int i =0 ; i <line.getLength() ; i++) {
Your update code, this should work fine:
private void OpenFile () throws ParserConfigurationException, SAXException, IOException {
JFileChooser of = new JFileChooser();
int option = of.showOpenDialog(of);
while (!of.getSelectedFile().getName().endsWith(".xml")) {
String error = "Error, Please select txt file";
JOptionPane.showMessageDialog(this, error, "Wrong type of file", JOptionPane.INFORMATION_MESSAGE);
of = new JFileChooser();
option = of.showOpenDialog(of);
}
if (option == JFileChooser.APPROVE_OPTION){
thisFile = new File(of.getSelectedFile().getPath());
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
Document doc = dBuilder.parse(thisFile);
doc.getDocumentElement().normalize();
NodeList nList = doc.getElementsByTagName("container");
Element line = (Element) nList.item(0);
for(int i =0 ; i < line.getLength() ; i++) {
Element point = (Element) line.getElementsByTagName("point").item(i);
x = Integer.parseInt(point.getElementsByTagName("X").item(0).getTextContent());
y = Integer.parseInt(point.getElementsByTagName("Y").item(0).getTextContent());
drewPoints(x, y);
pc.add(new Point(x, y));
}
}
}

Related

How to parse the next xml using XPath in java?I want to extract the cue and the xscope from a sentence?

This is my java code:
class SentenceNode {
Node xscope;
Node cue;
}
List<SentenceNode> getSentenceNodes(InputSource is) {
List<SentenceNode> sentenceNodes = new ArrayList<SentenceNode>();
try {
Object xscopes = XPathFactory
.newInstance()
.newXPath()
.evaluate("//xscope/cue", is,
XPathConstants.NODESET);
if (xscopes != null) {
NodeList cuesNodes = (NodeList) xscopes;
for (int i = 0; i < cuesNodes.getLength(); i++) {
SentenceNode sentenceNode = new SentenceNode();
Node cue = cuesNodes.item(i);
sentenceNode.cue = cue;
NodeList xscope = cue.getParentNode().getParentNode()
.getChildNodes();
for (int j = 0; j < xscope.getLength(); j++) {
Node n = xscope.item(j);
if (n.getNodeName().equals("xscope")) {
sentenceNode.xscope = n;
break;
}
}
sentenceNodes.add(sentenceNode);
}
}
} catch (Exception e) {
e.printStackTrace();
}
return sentenceNodes;
}
public void displaySentenceNodes() throws ClassNotFoundException, ClassCastException,
IOException {
InputSource is = new InputSource(new StringReader("TestBIO.xml"));
List<SentenceNode> nodes = getSentenceNodes(is);
for (SentenceNode node : nodes) {
System.out.println("Xscope: " + node.xscope.getTextContent());
System.out
.println("Cue: " + node.cue.getTextContent());
}
I want to extract from this xml the sentence with its cue and xscope.For each sentence I want to obtain the xscope and cue.If the sentence has more xscopes and more cues I want to obtain all.
Here is my xml:
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<Annotation created="22/2/2010" creator="BioscopeWriterCasConsumer">
<DocumentSet>
<Document type="Biological_abstract">
<DocID type="PMID">1984449</DocID>
<DocumentPart type="AbstractText">
<sentence>When cells were infected with HIV, no induction of NF-KB factor was detected, <xscope>whereas high level of progeny virions was produced, <cue>suggesting</cue> that</xscope>.</sentence>
<sentence> HIV <xscope><cue>could</cue> mimic some differentiation/activation stimuli allowing nuclear NF-KB expression</xscope>.</sentence>
</DocumentPart>
</Document>
</DocumentSet>
</Annotation>
An error occured when I am trying to parse the xml file.
[Fatal Error] :1:1: Content is not allowed in prolog.
org.xml.sax.SAXParseException; lineNumber: 1; columnNumber: 1; Content is not allowed in prolog.
at com.sun.org.apache.xerces.internal.parsers.DOMParser.parse(Unknown Source)
at com.sun.org.apache.xerces.internal.jaxp.DocumentBuilderImpl.parse(Unknown Source)
at com.sun.org.apache.xpath.internal.jaxp.XPathImpl.evaluate(Unknown Source)
You are missing ? Character in xml. Should start:
<?xml version="
I found the equivalent.Is like XPath but parse the xml with DOM parser bottom-up
Here is the code:
class SentenceNode {
Node xscope;
Node cue;
}
List<SentenceNode> extractElem(String file) throws ParserConfigurationException,
SAXException, IOException {
List<SentenceNode> sentenceNodes = new ArrayList<SentenceNode>();
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document document = builder.parse("Test1.xml");
document.getDocumentElement().normalize();
NodeList nList = document.getElementsByTagName("cue");
for (int temp = 0; temp < nList.getLength(); temp++) {
SentenceNode sentNode = new SentenceNode();
Node nodeCue = nList.item(temp);
sentNode.cue = nodeCue;
NodeList xscope = null;
if(nodeCue.getParentNode().getParentNode().getNodeName().equals("sentence")){
xscope = nodeCue.getParentNode().getParentNode()
.getChildNodes();
}
else if(nodeCue.getParentNode().getParentNode().getNodeName().equals("xscope")){
xscope = nodeCue.getParentNode().getParentNode().getParentNode()
.getChildNodes();
}
for (int j = 0; j < xscope.getLength(); j++) {
Node n = xscope.item(j);
if (n.getNodeName().equals("xscope")) {
sentNode.xscope = n;
break;
}
}
sentenceNodes.add(sentNode);
}
return sentenceNodes;
}
And it worked

Unable to delete a specific node in XML

I have an XML file and I need to delete a specific node. The node to be deleted will be defined dynamically based on the logic. I have been searching in internet for a solution but couldn't delete my node still. am getting error - NOT_FOUND_ERR: An attempt is made to reference a node in a context where it does not exist
Below is a sample XML File. I need to delete the node <NameValuePairs> which has <name>Local Variables</name>. Below is my sample XML Files Java Code
Sample XML File
<?xml version="1.0" encoding="UTF-8"?>
<DeploymentDescriptors xmlns="http://www.tibco.com/xmlns/dd">
<name>Test</name>
<version>1</version>
<DeploymentDescriptorFactory>
<name>RepoInstance</name>
</DeploymentDescriptorFactory>
<DeploymentDescriptorFactory>
<name>NameValuePairs</name>
</DeploymentDescriptorFactory>
<NameValuePairs>
<name>Global Variables</name>
<NameValuePair>
<name>Connections1</name>
<value>7222</value>
<requiresConfiguration>true</requiresConfiguration>
</NameValuePair>
<NameValuePair>
<name>Connections2</name>
<value>7222</value>
<requiresConfiguration>true</requiresConfiguration>
</NameValuePair>
</NameValuePairs>
<NameValuePairs>
<name>Local Variables</name>
<NameValuePair>
<name>Connections3</name>
<value>8222</value>
<requiresConfiguration>true</requiresConfiguration>
</NameValuePair>
<NameValuePair>
<name>Connections3</name>
<value>8222</value>
<requiresConfiguration>true</requiresConfiguration>
</NameValuePair>
</NameValuePairs>
</DeploymentDescriptors>
Java Code
File fDestFile = new File("myfile.xml");
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
Document oDoc3 = dBuilder.parse(fDestFile);
NodeList oDestFlowList = oDoc3.getElementsByTagName("NameValuePairs");
for (int m = 0; m < oDestFlowList.getLength(); m++) {
NodeList oDestchildList = oDestFlowList.item(m).getChildNodes();
for (int n = 0; n < oDestchildList.getLength(); n++) {
Node oDestchildNode = oDestchildList.item(n);
if ("name".equals(oDestchildNode.getNodeName())) {
//oDestchildNode.getParentNode().removeChild(oDestchildNode); //Not Working
//oDoc3.getDocumentElement().removeChild(oDestchildNode); //Not Working
}
}
}
}
You need create a separate reference from the parent node as an Element so that you aren't referencing the node that you are removing:
File fDestFile = new File("src/myfile.xml");
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = null;
try {
dBuilder = dbFactory.newDocumentBuilder();
Document oDoc3 = null;
oDoc3 = dBuilder.parse(fDestFile);
NodeList oDestFlowList = oDoc3.getElementsByTagName("NameValuePairs");
// Loop through all 'NameValuePairs'
for (int m = oDestFlowList.getLength()-1; m >=0 ; m--) {
NodeList oDestchildList = oDestFlowList.item(m).getChildNodes();
// Loop through children of 'NameValuePairs'
for (int n = oDestchildList.getLength()-1; n >=0 ; n--) {
// Remove children if they are of the type 'name'
if(oDestchildList.item(n).getNodeName().equals("name")){
oDestFlowList.item(m).removeChild(oDestchildList.item(n));
// For debugging
System.out.println(oDestchildList.item(n).getNodeName());
}
}
}
Source source = new DOMSource(oDoc3);
Result result = new StreamResult(fDestFile);
Transformer transformer = null;
transformer = TransformerFactory.newInstance().newTransformer();
// Transform your XML document (i.e. save changes to file)
transformer.transform(source, result);
} catch (Exception e) {
// Catch the exception here
e.printStackTrace();
}
}
If you are still having issues, then I would think that it is an issue with the node types. This was working for me before I put the check in for 'oDestchildNode.getNodeType()' but I would look at what type of node you are returning and go from there.
Here is the final piece of code that finally worked
public static void main(String[] args) {
File fXmlSubFile = new File("Sub.xml");
File fXmlOriginalFile = new File("Original.xml");
File fDestFile = new File("myfile.xml");
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder;
FileChannel source = null;
FileChannel destination = null;
XPath xPath = XPathFactory.newInstance().newXPath();
try{
if (!fDestFile.exists()) {
fDestFile.createNewFile();
}
source = new FileInputStream(fXmlOriginalFile).getChannel();
destination = new FileOutputStream(fDestFile).getChannel();
if (destination != null && source != null) {
destination.transferFrom(source, 0, source.size());
}
if (source != null) {
source.close();
}
if (destination != null) {
destination.close();
}
dBuilder = dbFactory.newDocumentBuilder();
Document oSubDoc = dBuilder.parse(fXmlSubFile);
Document oDestDoc = dBuilder.parse(fDestFile);
oSubDoc.getDocumentElement().normalize();
oDestDoc.getDocumentElement().normalize();
String sDestExpression = "/DeploymentDescriptors/NameValuePairs";
String sSubExpression = "/NameValuePairs";
NodeList nodeDestList = (NodeList) xPath.compile(sDestExpression).evaluate(oDestDoc, XPathConstants.NODESET);
NodeList nodeSubList = (NodeList) xPath.compile(sSubExpression).evaluate(oSubDoc, XPathConstants.NODESET);
for (int i = nodeDestList.getLength()-1; i >=0 ; i--) {
Node oDestNode = nodeDestList.item(i);
if (oDestNode.getNodeType() == Node.ELEMENT_NODE) {
Element oDestElement = (Element) oDestNode;
for (int j =0; j<nodeSubList.getLength(); j++) {
Node oSubNode = nodeSubList.item(j);
if (oSubNode.getNodeType() == Node.ELEMENT_NODE) {
Element oSubElement = (Element) oSubNode;
if(oDestElement.getElementsByTagName("name").item(0).getTextContent().equals(oSubElement.getElementsByTagName("name").item(0).getTextContent())){
oDestNode.getParentNode().removeChild(oDestNode);
}
}
}
}
}
Source src = new DOMSource(oDestDoc);
Result result = new StreamResult(fDestFile);
Transformer transformer = null;
transformer = TransformerFactory.newInstance().newTransformer();
// Transform your XML document (i.e. save changes to file)
transformer.transform(src, result);
}catch(Exception ex){
System.out.println("error:"+ex.getMessage());
ex.printStackTrace();
}
}

get data within a processing instruction tag in xml

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.

Java + reading data from XML file

What's wrong in this code? It gives me null everytime. I have no idea how to repair it, because in ordinary Java Application it works.
#WebMethod(operationName = "getColor")
public String getColor(#WebParam(name = "regNr") String regNr) {
String kolor=null;
try {
File fXmlFile = new File("/base.xml");
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
Document doc = dBuilder.parse(fXmlFile);
doc.getDocumentElement().normalize();
NodeList nList = doc.getElementsByTagName("person");
for (int temp = 0; temp < nList.getLength(); temp++) {
Node nNode = nList.item(temp);
if (nNode.getNodeType() == Node.ELEMENT_NODE) {
Element element = (Element) nNode;
String id = ""+ getValue("id",element);
if (regNr.equals(id)) {
color = element.getElementsByTagName("color").item(0).getTextContent();
return color;
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
return color;
}
I think (not sure because I don't know at which point it gives you null) you have to remove the / form the file name to become only base.xml

How to read alternative tags in xml using java?

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

Categories