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 コードを 1 つずつ読み取ることができます。

コード:

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 に答える