【发布时间】:2017-05-04 11:20:48
【问题描述】:
我想对大型 xml 文件使用 sax 解析器。处理程序看起来像这样:
DefaultHandler handler = new DefaultHandler() {
String temp;
HashSet < String > xml_Elements = new LinkedHashSet < String > ();
HashMap < String, Boolean > xml_Tags = new LinkedHashMap < String, Boolean > ();
HashMap < String, ArrayList < String >> tags_Value = new LinkedHashMap < String, ArrayList < String >> ();
//###startElement#######
public void startElement(String uri, String localName, String qName,
Attributes attributes) throws SAXException {
xml_Elements.add(qName);
for (String tag: xml_Elements) {
if (qName == tag) {
xml_Tags.put(qName, true);
}
}
}
//###########characters###########
public void characters(char ch[], int start, int length) throws SAXException {
temp = new String(ch, start, length);
}
//###########endElement############
public void endElement(String uri, String localName,
String qName) throws SAXException {
if (xml_Tags.get(qName) == true) {
if (tags_Value.containsKey(qName)) {
tags_Value.get(qName).add(temp);
tags_Value.put(qName, tags_Value.get(qName));
} else {
ArrayList < String > tempList = new ArrayList < String > ();
tempList.add(temp);
//tags_Value.put(qName, new ArrayList<String>());
tags_Value.put(qName, tempList);
}
//documentWriter.write(qName+":"+temp+"\t");
for (String a: tags_Value.keySet()) {
try {
documentWriter.write(tags_Value.get(a) + "\t");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
xml_Tags.put(qName, false);
}
tags_Value.clear();
}
};
我的 xml 是这样的:
<TermInfo>
<A>1/f noise</A>
<B>Random noise</B>
<C>Accepted</C>
<D>Flicker noise</D>
<F>Pink noise</F>
<I>1-f</I>
<I>1/f</I>
<I>1/f noise</I>
<I>1:f</I>
<I>flicker noise</I>
<I>noise</I>
<I>pink noise</I>
<ID>1</ID>
</TermInfo>
<TermInfo>
<A>3D printing</A>
<B>Materials fabrication</B>
<C>Accepted</C>
<D>3d printing</D>
<F>2</F>
<I>three dimension*</I>
<I>three-dimension*</I>
<I>3d</I>
<I>3-d</I>
<I>3d*</I>
</TermInfo>
我想将所有嵌套标签聚集在标签 A 下。 即对于每个 A.. 它的 B、C、D 和 I 在一起.. 等等。但是使用上面的处理程序,输出就像 A-B-C-D-I-I-etc 。我可以为每个 A 制作一个对象并在其中添加其他元素吗?我怎样才能包括这个..
【问题讨论】: