问题描述
我在理解使用 SAX 解析 XML 结构时遇到了一些麻烦.假设有以下 XML:
I have some trouble understanding parsing XML structures with SAX. Let's say there is the following XML:
<root>
<element1>Value1</element1>
<element2>Value2</element2>
</root>
和一个字符串变量myString
.
通过方法 startElement、endElement() 和 characters() 很容易.但我不明白如何实现以下目标:
Just going through with the methods startElement, endElement() and characters() is easy. But I don't understand how I can achieve the following:
如果当前元素等于 element1
,则将其值 value1
存储在 myString
中.据我所知,没有什么像:
If the current element equals element1
store its value value1
in myString
. As far as I understand there is nothing like:
if (qName.equals("element1")) myString = qName.getValue();
猜猜我只是想得太复杂了:-)
Guess I'm just thinking too complicated :-)
罗伯特
推荐答案
使用 SAX,您需要维护自己的堆栈.对于非常基本的处理,您可以执行以下操作:
With SAX you need to maintain your own stack. You can do something like this for very basic processing:
void startElement(...) {
if (name.equals("element1")) {
inElement1 = true;
element1Content = new StringBuffer();
}
}
void characters(...) {
if (inElement1) {
element1Content.append(characterData);
}
}
void endElement(...) {
if (name.equals("element2")) {
inElement1 = false;
processElement1Content(element1Content.toString());
}
}
如果您想要示例中的代码,那么您需要使用 DOM 模型而不是 SAX.DOM 更容易编写代码,但通常比 SAX 更慢且内存成本更高.
If you want code as in your example then you need to use the DOM model rather than SAX. DOM is easier to code up but is generally slower and more memory expensive than SAX.
我建议使用第三方库而不是内置的 Java XML 库来进行 DOM 操作.Dom4J 看起来不错,但可能还有其他库.
I recommend using a third-party library rather than the built-in Java XML libraries for DOM manipulation. Dom4J seems pretty good but there are probably other libraries out there too.
这篇关于SAX:如何获取元素的内容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!