Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
383 views
in Technique[技术] by (71.8m points)

java - How to know what child is belonging to their parent?

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

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

1 Reply

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...