开发者

How can i parse the following XML using JDOM

开发者 https://www.devze.com 2023-04-01 01:26 出处:网络
I have an XML document as follows: <?xml version=\"1.0\" encoding=\"UTF-8\"?> <decision> <question id=\"0\">

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">
 开发者_StackOverflow社区       <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.


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.


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.


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

0

精彩评论

暂无评论...
验证码 换一张
取 消