【发布时间】:2015-03-03 17:18:43
【问题描述】:
我有一个 XML 格式的模型,如下所示,我需要解析 XML 并检查我的 XML 是否将 internal-flag 标志设置为真。在我的其他模型中,internal-flag 标志可能设置为 false。有时,这个字段也可能不存在,所以默认情况下,我的代码中它是 false。
<?xml version="1.0"?>
<ClientMetadata
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.google.com client.xsd"
xmlns="http://www.google.com">
<client id="200" version="13">
<name>hello world</name>
<description>hello hello</description>
<organization>TESTER</organization>
<author>david</author>
<internal-flag>true</internal-flag>
<clock>
<clock>
<for>
<init>val(tmp1) = 1</init>
<clock>
<eval><![CDATA[result("," + $convert(val(tmp1)))]]></eval>
</clock>
</for>
<for>
<incr>val(tmp1) -= 1</incr>
<clock>
<eval><![CDATA[result("," + $convert(val(tmp1)))]]></eval>
</clock>
</for>
</clock>
</clock>
</client>
</ClientMetadata>
我有一个 POJO,我在其中存储我的上述模型 -
public class ModelMetadata {
private int modelId;
private String modelValue; // this string will have my above XML data as string
// setters and getters here
}
现在确定我的模型是否将 internal-flag 设置为 true 的最佳方法是什么?
// this list will have all my Models stored
List<ModelMetadata> metadata = getModelMetadata();
for (ModelMetadata model : metadata) {
// my model will be stored in below variable in XML format
String modelValue = model.getModelValue();
// now parse modelValue variable and extract `internal-flag` field property
}
我需要为此使用 XML 解析还是有更好的方法来做到这一点?
更新:-
我已经开始使用 Stax,这是我迄今为止尝试过的,但不确定如何提取该字段 -
InputStream is = new ByteArrayInputStream(modelValue.getBytes());
XMLStreamReader r = XMLInputFactory.newInstance().createXMLStreamReader(is);
while(r.hasNext()) {
// now what should I do here?
}
【问题讨论】:
-
如何从 XML 中填充您的 bean?您如何获得所有其他字段(例如“名称”)?
-
@Thilo,到目前为止,我还没有对 XML 做任何事情。在我的
ModelMetadata类中,有一个名为modelValue的变量——这个变量以字符串格式存储我的XML,这意味着我需要使用String modelValue = model.getModelValue();来进行XML 解析。 -
有关 XML 解析选项,请参阅此stackoverflow.com/questions/23509480/…
-
@Thilo 我开始使用 Stax 解析我的 XML,但卡住了。我已经用我拥有的代码更新了问题。