-->

How can i parse the following XML using JDOM

2020-03-31 08:34发布

问题:

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.



标签: java xml jdom