gpt4 book ai didi

java - 解析要在 java servlet 中使用的 XMl

转载 作者:行者123 更新时间:2023-12-01 15:02:56 25 4
gpt4 key购买 nike

我的 XML 如下

<result cover="http://ia.mediaimdb.com/images      
/M/MV5BMjMyOTM4MDMxNV5BMl5BanBnXkFtZTcwNjIyNzExOA@@._V1._SX54_
CR0,0,54,74_.jpg" title="The Amazing Spider-Man(2012)"year="2012"
director="Marc Webb" rating="7.5"
details="http://www.imdb.com/title/tt0948470"/>

<result cover="http://ia.mediaimdb.
com/images/M/MV5BMzk3MTE5MDU5NV5BMl5BanBnXkFtZTYwMjY3NTY3._V1._SX54_CR0,
0,54,74_.jpg" title="Spider-Man(2002)" year="2002"director="Sam Raimi"
rating="7.3" details="http://www.imdb.com/title/tt0145487"/>

<result cover="http://ia.mediaimdb.
com/images/M/MV5BODUwMDc5Mzc5M15BMl5BanBnXkFtZTcwNDgzOTY0MQ@@._V1._SX54_
CR0,0,54,74_.jpg" title="Spider-Man 3 (2007)" year="2007" director="Sam
Raimi" rating="6.3" details="http://www.imdb.com/title/tt0413300"/>

<result cover="http://i.mediaimdb.
com/images/SF1f0a42ee1aa08d477a576fbbf7562eed/realm/feature.gif" title="
The Amazing Spider-Man 2 (2014)" year="2014" director="Sam Raimi"
rating="6.3" details="http://www.imdb.com/title/tt1872181"/>

<result cover="http://ia.mediaimdb.
com/images/M/MV5BMjE1ODcyODYxMl5BMl5BanBnXkFtZTcwNjA1NDE3MQ@@._V1._SX54_
CR0,0,54,74_.jpg" title="Spider-Man 2 (2004)" year="2004" director="Sam
Raimi" rating="7.5" details="http://www.imdb.com/title/tt0316654"/>
</results>

我需要使用像 saxp 这样的解析器解析这个 XML 文件,并将结果输出为 json 字符串。我是 SAXParser 的新手。这段时间我一直在谷歌搜索,但我无法简单地理解它。

有什么想法吗?

最佳答案

让我用一个简单的例子来解释一下。

输入 XML:

<Employees>
<employee name="vels" gender="male"/>
<employee name="steave" gender="male"/>
</Employees>

使用 SAXParser 解析 xml

final JSONObject jsonObj = new JSONObject();
SAXParserFactory factory = SAXParserFactory.newInstance();
SAXParser saxParser = factory.newSAXParser();

DefaultHandler handler = new DefaultHandler() {
@Override
public void startElement(String uri, String localName, String qName,
Attributes attributes) throws SAXException {
try {
if (qName.equals("Employees")) {
// reject root node
return;
}
int len = attributes.getLength();
HashMap<String, String> map = new HashMap< String, String>();
for (int i = 0; i < len; i++) {
String attribName = attributes.getLocalName(i);
String attribVal = attributes.getValue(i);
map.put(attribName, attribVal);


}
jsonObj.append("employee", map);
} catch (JSONException ex) {
// handle excep
}

}
};

saxParser.parse("c:/employee.xml", handler);
String jSonOutput = jsonObj.toString();
// process this json outpout
System.out.println(jSonOutput);

输出(手动格式化):

   {"employee":
[
{"name":"vels","gender":"male"},
{"name":"steave","gender":"male"}
]
}

这是 Java SAX Parser & Java SAX DefaultHandler 的一个简单而体面的示例。希望你能继续前进。

关于java - 解析要在 java servlet 中使用的 XMl,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13372900/

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