Jump to content
kynder

java parse help

Recommended Posts

parsez un document xml cu dom parser in java si am nevoie de ajutor in legatura cu urmatoarea problema :

este posibil sa citesc din xml un tag din interiourl altui tag?

<root>

<ceva>

<nume>

alaa

</nume>

<tag>

<x>4</x>

<y>5</y>

</tag>

</ceva>

<ceva> alta componenta..</ceva

</root>

adica sa pot sa citesc valorile lui x si y din interiorul <tag>?

Edited by kynder
Link to comment
Share on other sites

Eu am lucrat cu JDOM, cand am avut de a face cu fisiere xml.

Iti las mai jos o clasa ca sa intelegi cam cum merge. Nu am commenturi ca a trebuit sa il termin repede si dupa nu ma mai interesat sa le pun.

package com.m2g.books.Model;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.List;
import java.util.TreeMap;

import org.jdom.Document;
import org.jdom.Element;
import org.jdom.JDOMException;
import org.jdom.input.SAXBuilder;
import org.jdom.output.Format;
import org.jdom.output.XMLOutputter;

public class BookParser implements XMLParser{

private TreeMap<String, Object> booksTree;
private File xmlFile;
private SAXBuilder builder;

public BookParser(){

booksTree = new TreeMap<String, Object>();
builder = new SAXBuilder();
xmlFile = new File("src/com/m2g/books/data/books.xml");

}

@Override
public void parse() {

try {

Document document = (Document) builder.build(xmlFile);
Element rootNode = document.getRootElement();

@SuppressWarnings("rawtypes")
List list = rootNode.getChildren("book");

for (int i = 0; i < list.size(); i++) {

Element node = (Element) list.get(i);

String ISBN = node.getAttributeValue("ISBN");
String Title = node.getChildText("Title");
String Author = node.getChildText("Author");
String Genre = node.getChildText("Genre");
String Price = node.getChildText("Price");
String Quantity = node.getChildText("Quantity");

int price = Integer.parseInt(Price);
int qty = Integer.parseInt(Quantity);

Book b = new Book(Title, Author, Genre, ISBN, price, qty);
booksTree.put(ISBN, ;
}
} catch (JDOMException e) {

e.printStackTrace();
} catch (IOException e) {

e.printStackTrace();
}


}

@Override
public TreeMap<String, Object> getElemetsTree() {

return booksTree;
}

@Override
public void addElement(Object el) {
Book added = (Book) el;

try {

SAXBuilder builder = new SAXBuilder();
File xmlFile = new File("src/com/m2g/books/data/books.xml");

Document doc = (Document) builder.build(xmlFile);
Element rootNode = doc.getRootElement();

String price = Integer.toString(added.getPrice());
String qty = Integer.toString(added.getQty());

Element ISBN = new Element("book").setAttribute("ISBN", added.getIsbn());
Element Title = new Element("Title").setText(added.getTitle());
Element Author = new Element("Author").setText(added.getAuthor());
Element Genre = new Element("Genre").setText(added.getGenre());
Element Price = new Element("Price").setText(price);
Element Quantity = new Element("Quantity").setText(qty);

ISBN.addContent(Title);
ISBN.addContent(Author);
ISBN.addContent(Genre);
ISBN.addContent(Price);
ISBN.addContent(Quantity);
rootNode.addContent(ISBN);

XMLOutputter xmlOutput = new XMLOutputter();

xmlOutput.setFormat(Format.getPrettyFormat());
xmlOutput.output(doc , new FileWriter("src/com/m2g/books/data/books.xml"));

} catch (IOException io) {
io.printStackTrace();
} catch (JDOMException e) {
e.printStackTrace();
}

}

@Override
public void deleteElement(Object el) {
Book toDelete = (Book) el;
try {

SAXBuilder builder = new SAXBuilder();
File xmlFile = new File("src/com/m2g/books/data/books.xml");

Document doc = (Document) builder.build(xmlFile);
Element rootNode = doc.getRootElement();
@SuppressWarnings("rawtypes")
List books = rootNode.getChildren("book");

for (int i = 0; i < books.size(); i++) {
Element node = (Element) books.get(i);
if (toDelete.getIsbn().equals(node.getAttributeValue("ISBN"))) {
rootNode.removeContent(node);
}
}

XMLOutputter xmlOutput = new XMLOutputter();


xmlOutput.setFormat(Format.getPrettyFormat());
xmlOutput.output(doc , new FileWriter("src/com/m2g/books/data/books.xml"));

booksTree = new TreeMap<String, Object>();

} catch (IOException io) {
io.printStackTrace();
} catch (JDOMException e) {
e.printStackTrace();
}

}

@Override
public void updateElement(Object el, String oldISBN) {
Book toUpdate = (Book) el;

try {

SAXBuilder builder = new SAXBuilder();
File xmlFile = new File("src/com/m2g/books/data/books.xml");

Document doc = (Document) builder.build(xmlFile);
Element rootNode = doc.getRootElement();
@SuppressWarnings("rawtypes")
List users = rootNode.getChildren("book");

for (int i = 0; i < users.size(); i++) {
Element node = (Element) users.get(i);

if (oldISBN.equals(node.getAttributeValue("ISBN"))) {
String price = Integer.toString(toUpdate.getPrice());
String qty = Integer.toString(toUpdate.getQty());

node.getChild("Title").setText(toUpdate.getTitle());
node.getChild("Author").setText(toUpdate.getAuthor());
node.getChild("Genre").setText(toUpdate.getGenre());
node.getChild("Price").setText(price);
node.getChild("Quantity").setText(qty);
node.getAttribute("ISBN").setValue(toUpdate.getIsbn());

}
}


XMLOutputter xmlOutput = new XMLOutputter();


xmlOutput.setFormat(Format.getPrettyFormat());
xmlOutput.output(doc , new FileWriter("src/com/m2g/books/data/books.xml"));

booksTree = new TreeMap<String, Object>();

} catch (IOException io) {
io.printStackTrace();
} catch (JDOMException e) {
e.printStackTrace();
}

}



}

Aici ai fisierul xml pe care poti sa il folosesti pentru test.

<?xml version="1.0" encoding="UTF-8"?>
<Library>
<book ISBN="0061804193">
<Title>The Cove: A Novel</Title>
<Author>Ron Rash</Author>
<Genre>Novel</Genre>
<Price>51</Price>
<Quantity>28</Quantity>
</book>
<book ISBN="1430272058 ">
<Title>Pro WPF in C# 2010: Windows Presentation Foundation in .NET 4</Title>
<Author>Matthew MacDonald</Author>
<Genre>Technical</Genre>
<Price>60</Price>
<Quantity>0</Quantity>
</book>
<book ISBN="12">
<Title>Calico Joe</Title>
<Author>John Grisham</Author>
<Genre>Novel</Genre>
<Price>323</Price>
<Quantity>5</Quantity>
</book>
<book ISBN="0312380828">
<Title>Come Home</Title>
<Author>Lisa Scottoline</Author>
<Genre>Novel</Genre>
<Price>45</Price>
<Quantity>15</Quantity>
</book>
<book ISBN="0596009208 ">
<Title>Head First Java, 2nd Edition</Title>
<Author>Kathy Sierra</Author>
<Genre>Technical</Genre>
<Price>58</Price>
<Quantity>35</Quantity>
</book>
</Library>

Bun!

Uita-te in metoda parse() din acea clasa si vezi ce se intampla.

Se ia elementul radacina:

Element rootNode  = document.getRootElement();

Apoi se creaza o lista cu toti copii acelui root node care au numele/tagul "book":

List list = rootNode.getChildren("book");

Se parcurge acea lista si se extrag copii lui book.

Faci similar si pentru a intra mai adanc in structura. Nu am timp sa stau sa explic acum dar ruleaza niste exemple si o sa intelegi.

Bafta!

Link to comment
Share on other sites

Nu sunt prea familiar cu dorm parser, dar cred ca ar fi de ajuns daca ai trata intregul fragment ca pe un simplu sir si-l vei itera liniar pastrand in stiva (container sau functie recursiva) ultimul/ultimile tag(uri) din care ai venit ca sa ajungi in x respectiv y si apoi daca locul din care ai venit corespunde cu tagul cautat de tine atunci ceea ce urmeaza dupa x> si respectiv y> sunt valorile pe care le cauti si in momentul ala poti opri si algoritmul sa nu stai sa mai cauti mai departe.

Daca observi un anumit model static, adica sa ai mereu <tag><x> si imediat dupa valoare si inchidere sa ai <y> si sa stii mereu dinainte ce tip de x si y cauti fara a fi nevoie de o preparsare, atunci poti cauta direct in sir subsirul respectiv, dupa care ce e scris mai departe reprezinta datele relevante, iar pentru urmatoare cautari specifici indexul de start ca fiind cel returnat de cautarea anterioara astfel nu vei trece din nou prin acelasi text si nici nu vei avea false pozitive in caz de existenta a mai multor taguri cu acelasi nume.

Link to comment
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.



×
×
  • Create New...