gpt4 book ai didi

Java Xml 元素 - 获取文件中的节点位置

转载 作者:太空宇宙 更新时间:2023-11-04 13:19:33 27 4
gpt4 key购买 nike

我有 XML 文件,我想获取节点的位置。

<Root>
<Node1></Node1>
</Root>

我想得到1)开始和结束位置; 2) 起始线和结束线

如何做到这一点?谢谢

最佳答案

创建一个读取器来跟踪您想要的位置信息:

static public class MyReader extends Reader {

final private Reader internalReader;
private int pos;
private int line;

public MyReader(Reader internalReader) {
this.internalReader = internalReader;
}

public int getPos() {
return pos;
}

public int getLine() {
return line;
}


@Override
public int read(char[] cbuf, int off, int len) throws IOException {

int chars_read = internalReader.read(cbuf, off, 1);
pos += chars_read;
if(cbuf[off] =='\n' && chars_read > 0) {
line++;
}
return chars_read;
}

@Override
public void close() throws IOException {
internalReader.close();
}
}

将其与 ContentHandler 结合使用,将位置信息存储在与元素关联的某些数据结构中。

    String xmlString = "<Root>\n"
+ " <Node1></Node1>\n"
+ "</Root>";
StringReader strReader = new StringReader(xmlString);
MyReader reader = new MyReader(strReader);
SAXParserFactory factory = SAXParserFactory.newInstance();
SAXParser parser = factory.newSAXParser();
XMLReader xmlreader = parser.getXMLReader();
Map<String,List<Integer>> startMap = new HashMap<>();
Map<String,List<Integer>> endMap = new HashMap<>();
Map<String,List<Integer>> startLineMap = new HashMap<>();
Map<String,List<Integer>> endLineMap = new HashMap<>();

DefaultHandler handler = new DefaultHandler() {

@Override
public void endElement(String uri, String localName, String qName) throws SAXException {
super.endElement(uri, localName, qName); //To change body of generated methods, choose Tools | Templates.
List<Integer> l = endMap.get(qName);
if(null == l) {
l = new ArrayList<>();
}
l.add(reader.getPos());
endMap.put(qName, l);
List<Integer> ll = endLineMap.get(qName);
if(null == ll) {
ll= new ArrayList<>();
}
ll.add(reader.getLine());
endLineMap.put(qName, ll);
}

@Override
public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {
super.startElement(uri, localName, qName, attributes); //To change body of generated methods, choose Tools | Templates.
List<Integer> l = startMap.get(qName);
if(null == l) {
l = new ArrayList<>();
}
l.add(reader.getPos());
startMap.put(qName, l);
List<Integer> ll = startLineMap.get(qName);
if(null == ll) {
ll= new ArrayList<>();
}
ll.add(reader.getLine());
startLineMap.put(qName, ll);
}
};
xmlreader.setContentHandler(handler);
xmlreader.parse(new InputSource(reader));
System.out.println("startMap = " + startMap);
System.out.println("endMap = " + endMap);
System.out.println("startLineMap = " + startLineMap);
System.out.println("endLineMap = " + endLineMap);

关于Java Xml 元素 - 获取文件中的节点位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33217150/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com