Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I have a XML-file with over 12k tags. All the tags have a tagId, like:

<first_tag>                   tagId = 1
   <second_tag_first_child>   tagId = 2

So on, so forth.

In addition to tagId they all need to have an parentId, so the child know what parent they belong to.

<root_tag>                               parentId = 0 | tagId = 1
  <first_tag>                            parentId = 1 | tagId = 2
     <second_tag_first_child>            parentId = 2 | tagId = 3
     <third_tag_second_child>            parentId = 2 | tagId = 4
        <fourth_tag_first_grandchild>    parentId = 4 | tagId = 5
  <fifth_tag>                            parentId = 1 | tagId = 6

Does anyone know how to make the logic so i can get the parentId? What I need is a System.out.println(tag + parentId + tagId + " ")

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
382 views
Welcome To Ask or Share your Answers For Others

1 Answer

You have an XML-file and you want to read it with a Java-program. You could either go through hell and write your own program to read XML-files, or you use already existing packages for that, for example the SAX-library.

To use SAX-parser use these import-statements:

import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;

You have to create a SAX-parser from a SAXParserFactory. The factory itself is created with a static factory-method.

SAXParserFactory f = SAXParserFactory.newInstance();
SAXParser parser = factory.newSAXParser();

You use parser to read the XML-file and give the output to DefaultHandler. Everything is handled by DefaultHandler so there is where your code goes.

Documentation of DefaultHandler


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...