如何通过SAX解析XML并创建树列表?
我已经学习了关于 java 的 SAX 解析器的教程,现在我需要创建这样的 XML 文件的树列表:
<course>
<chapter>
<title>chapter one of course one</title>
<content> .... </content>
</chapter>
<chapter>
<title>chapter two of course one</title>
<content> .... </content>
</chapter>
</course>
然后我要创建这样的数据结构:
string lessons[][] = {
{"chapter one of course one", "chapter two of course one"},
{"chapter one of course two", "chapter two of course two", "chapter tree of course two"},
....
....
}
I have learned a tutorial about SAX parser of java and now I need to create tree list of XML file like this:
<course>
<chapter>
<title>chapter one of course one</title>
<content> .... </content>
</chapter>
<chapter>
<title>chapter two of course one</title>
<content> .... </content>
</chapter>
</course>
and then I what to create data structure like this:
string lessons[][] = {
{"chapter one of course one", "chapter two of course one"},
{"chapter one of course two", "chapter two of course two", "chapter tree of course two"},
....
....
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
JDK 中没有对您正在寻找的数据结构类型提供开箱即用的支持。您需要的是Multimap。 Guava 库提供了这种数据结构。您可以使用该库(我推荐)或构建您自己的库。
另外,请确保您阅读我的答案在此如果您正在使用 SAX 读取元素内容,请发布此帖子。
JAVA SAX 解析器拆分调用字符()
There is no out-of-box support in JDK for the kind of data structure you are looking for. What you need is a Multimap. Guava library provides this data structure. You can either use that library (I recommend) or build your own.
Also, make sure you read my answer in this SO post if your are reading element content using SAX.
JAVA SAX parser split calls to characters()
给你:THIS 是 SAX 文档,阅读并尝试构建您自己的解析器伙伴
here you go: THIS is SAX documentation, read and try to build your own parser mate
考虑aa 堆栈。在 startElement() 中压入,在 endElement 中弹出()。根据元素标签名称,您可以对堆栈上的内容以及“全局”上下文中的内容进行有趣的操作。
Think in terms of a a Stack. In startElement() you push and in endElement you pop(). Depending on the element tag name you do interesting stuff with what's on the stack and perhaps also what you have in a "global" context.
这段代码完全符合您的要求,您只需调整它即可输出您想要的 JSON 结构。
https://github.com/kasmodia/sax-tree-parser
This code exactly does what you're looking for, You just need to tweak it to output the JSON structure you want.
https://github.com/kasmodia/sax-tree-parser