How can i parse the following XML using JDOM

走远了吗. 提交于 2019-12-01 12:45:30

问题


I have an XML document as follows:

<?xml version="1.0" encoding="UTF-8"?>

<decision>
  <question id="0">
    <questionText>What type is your OS?</questionText>
    <answer id="0">
      <answerText>windows</answerText>
    </answer>
    <answer id="1">
      <answerText>linux</answerText>
    </answer>
    <answer id="2">
      <answerText>mac</answerText>
    </answer>
  </question>
  <question id="1">
    <questionText>What are you looking for?</questionText>
    <answer id="0">
      <answerText>table</answerText>
      <question id="0">
        <questionText>Which color table you want?</questionText>
        <answer id="0">
          <answerText>green</answerText>
        </answer>
        <answer id="1">
          <answerText>black</answerText>
        </answer>
        <answer id="2">
          <answerText>pink</answerText>
        </answer>
      </question>
    </answer>
    <answer id="1">
      <answerText>chair</answerText>
    </answer>
    <answer id="2">
      <answerText>bed</answerText>
    </answer>
    <answer id="3">
      <answerText>cloth</answerText>
    </answer>
  </question>

Now I want to parse the above XML using jdom in Java. It kind of recursive and important thing to note is a Question can't be a direct child of Question and same applies for Answer.


回答1:


Article

In the light of previous related questions, I'd like to repeat and stress the advice of others (like JB Nizet commented on this question):

Learn Java, learn XML, pick the tools and API's you need for your project and learn to use those too. If at one point you get into trouble, everybody here will be happy to help you out debugging your code.

I'm aware that this may seem harsh but it gets to the point where your program gets built by StackOverflow users and not yourself.

That being said, the link at the top of this answer leads to a tutorial on using JDOM to traverse your XML.




回答2:


Use Element.getChildren(String) to get all of the question tags and loop through that List - calling getChildren(String) to get all of the answers, or getChild(String) if there can be only one child element.




回答3:


first that you need use is XSD to validate the XML.



来源:https://stackoverflow.com/questions/7231993/how-can-i-parse-the-following-xml-using-jdom

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!