0

我有xml文件

<A>
   <A1>
      <A2>Hi</A2>
   </A1>
<A>
<B>
   <B1></B1>
   <B2>100</B2>
</B>
<A>
   <A1>
      <A2>Hello</A2>
   </A1>
<A>
<B>
   <B1>1000</B1>
   <B2></B2>
</B>

同样,这也超过 10 个街区。现在我的java代码能够一个一个地读取,在读取标签之后首先读取所有内容。

代码:

public class XMLParse {
    static Document doc;
 public static void main(String argv[]) {
  try {
  File file = new File("/home/dev042/Desktop/xxx.xml");
  DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
  DocumentBuilder db = dbf.newDocumentBuilder();
  doc = db.parse(file);
  doc.getDocumentElement().normalize();
  System.out.println("Root element " + doc.getDocumentElement().getNodeName());
  NodeList nodeLst = doc.getElementsByTagName("A");
  System.out.println("Information of all Balence Sheet");
 int count = nodeLst.getLength();
 String name;
  for (int s = 0; s < nodeLst.getLength(); s++) {

    Node fstNode = nodeLst.item(s);

    if (fstNode.getNodeType() == Node.ELEMENT_NODE) {
      Element fstElmnt = (Element) fstNode;
      NodeList fstNmElmntLst = fstElmnt.getElementsByTagName("A1");
      for(int i =0; i < fstNmElmntLst.getLength(); i++ )
      {
          Node lst = fstNmElmntLst.item(i);
          if(lst.getNodeType() == Node.ELEMENT_NODE)
          {
              Element fsttravel = (Element) lst;
              NodeList secNmElt = fsttravel.getElementsByTagName("*");
               name = secNmElt.item(0).getTextContent();
               System.out.println("Name : "  + name);
          }
      }
    }

  }
}
   catch (Exception e) {
    e.printStackTrace();
  }
  String amt;
  double amount;
  NodeList nodeLst = doc.getElementsByTagName("B");
   int coun = nodeLst.getLength();
  for (int s = 0; s < nodeLst.getLength(); s++) {
      Node secNode = nodeLst.item(s);

     if (secNode.getNodeType() == Node.ELEMENT_NODE) {
       try
              {
                Element amtval = (Element) secNode;
                NodeList secval = amtval.getElementsByTagName("B1");
                amt = secval.item(0).getTextContent();
                //amount = Double.parseDouble(amt);
                System.out.println("SubAmt :" + amt);

                NodeList lstNmElmntLst = amtval.getElementsByTagName("B2");
                amt = lstNmElmntLst.item(0).getTextContent();
                System.out.println("MainAmt : " +amt);
              }
              catch(Exception ex){
                  ex.printStackTrace();
             }
     }
  }

 }
}

电流输出:

Hi
Hello
100
1000

我想交替阅读标签。那么只有我可以映射这些值。我怎样才能交替阅读这些标签。输出应该是这样的

Hi 100
Hello 1000

请帮我摆脱它。提前致谢..

4

1 回答 1

1

我认为您只需要过滤标签,以便您的解析器仅获取标签。为此,您可以使用XPath. 这是此处的示例:

http://www.roseindia.net/tutorials/xPath/java-xpath.shtml

于 2012-05-02T08:43:16.777 回答