我希望在使用java StAX2解析器解析XML时获得元素路径。如何获取有关当前元素路径的信息?
<root>
<a><b>x</b></a>
</root>在本例中,路径是/root/a/b。
发布于 2016-12-13 09:20:15
留一堆。在START_ELEMENT上推送元素名,并在END_ELEMENT上弹出它。
下面是一个简短的例子。它只会打印正在处理的元素的路径。
public static void main(String[] args) throws IOException, XMLStreamException {
try (FileInputStream in = new FileInputStream("test.xml")) {
XMLInputFactory factory = XMLInputFactory.newFactory();
XMLStreamReader reader = factory.createXMLStreamReader(in);
LinkedList<String> path = new LinkedList<>();
int next;
while ((next = reader.next()) != XMLStreamConstants.END_DOCUMENT) {
switch (next) {
case XMLStreamConstants.START_ELEMENT:
// push the name of the current element onto the stack
path.addLast(reader.getLocalName());
// print the path with '/' delimiters
System.out.println("Reading /" + String.join("/", path));
break;
case XMLStreamConstants.END_ELEMENT:
// pop the name of the element being closed
path.removeLast();
break;
}
}
}
}发布于 2016-12-15 01:23:59
“编年史上的责任”
方法1:专用堆栈@teppic建议
try (InputStream in = new ByteArrayInputStream(xml.getBytes())) {
final XMLInputFactory2 factory = (XMLInputFactory2) XMLInputFactory.newInstance();
final XMLStreamReader2 reader = (XMLStreamReader2) factory.createXMLStreamReader(in);
Stack<String> pathStack = new Stack<>();
while (reader.hasNext()) {
reader.next();
if (reader.isStartElement()) {
pathStack.push(reader.getLocalName());
processPath('/' + String.join("/", pathStack));
} else if (reader.isEndElement()) {
pathStack.pop();
}
}
}方法2(丑陋):黑客攻击伍德斯托克斯氏 InputElementStack
InputElementStack、其受保护的mCurrElement和插入父级(这会减慢algoritm)。
包com.ctc.wstx.sr;导入java.util.LinkedList;公共类StackUglyAdapter {公共静态字符串PATH_SEPARATOR = "/";私有InputElementStack堆栈;公共StackUglyAdapter(InputElementStack堆栈){ this.stack =堆栈;}公共字符串getCurrElementLocalName() {返回this.stack.mCurrElement.mLocalName;}公共字符串getCurrElementPath() { LinkedList列表=新LinkedList();元素el = this.stack.mCurrElement;时间(el != null) { list.addFirst(el.mLocalName);el = el.mParent;}返回PATH_SEPARATOR+String.join(PATH_SEPARATOR,list);}具有专用堆栈的方法1更好,因为它与API实现无关,并且与方法2一样快。
https://stackoverflow.com/questions/41108090
复制相似问题