节点值内的Java XML节点

时间:2016-05-12 09:06:19

标签: java xml xml-parsing

我有一个像这样的xml:

<cargalery>
   <garage garagetype="Expensive" garagename="Garage1">
      <cars cartype="faster" carname="Car4" />
      <cars cartype="faster" carname="Car5" />
      <cars cartype="slower" carname="Car6" />
   </garage>
   <garage garagetype = "Cheap" garagename="Garage2">
      <cars cartype="slower" carname="Car1" />
      <cars cartype="faster" carname="Car2" />
      <cars cartype="slower" carname="Car3" />
   </garage>
</cargalery>

我可以通过以下方式阅读车库节点:

DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
URL u = new URL("xmlurl");
Document doc = builder.parse(u.openStream());
doc.getDocumentElement().normalize();

System.out.println("Root element :" + doc.getDocumentElement().getNodeName());      
NodeList NodeOzet = doc.getElementsByTagName("garage");     

for (int temp = 0; temp < NodeOzet.getLength(); temp++) 
{
  Node nOzet = NodeOzet.item(temp);
  System.out.println("\nCurrent Element :" + nOzet.getNodeName());

  if (nOzet.getNodeType() == Node.ELEMENT_NODE) 
  {
    Element eElement = (Element) nOzet;    
    System.out.println("Garage Name : " + eElement.getAttribute("garagename"));  
  }
}

但我无法阅读车内的车库。我如何阅读车库内的车辆?

感谢。

4 个答案:

答案 0 :(得分:1)

对于Element定义方法getAttribute("AttributeName")

如果你想通过标签名称&#34;车库&#34;在所有元素中创建一个NodeList,你想要一个车库内的汽车名称,那么你应该创建一个嵌套的for循环,按标签名称获取所有元素&#34;汽车&#34;在车库内。

    for (int temp = 0; temp < NodeOzet.getLength(); temp++){
        Node nOzet = NodeOzet.item(temp);
        NodeList carList = eElement.getElementsByTagName("cars")
        String cars = "";
        for(int temp2 = 0; temp2 < carList.getLength(); temp2++){
             cars += ((Element)carList.item(temp2)).getAttribute("carname") + "\t";
        }
     }

对于每个车库都是如此,你可以获得车库内的所有车辆以及他们的名字

答案 1 :(得分:0)

在xml中,一切都是从注释到文本的节点。您可以获取此元素的所有子节点,然后获取元素节点的属性。在if语句中附加以下代码。

NodeList childNodes = eElement.getChildNodes();
for(int i = 0; i < childNodes.getLength(); i++){
    Node item = childNodes.item(i);
    if(item.getNodeType() != Node.ELEMENT_NODE){
        continue;
    }
    NamedNodeMap attributes = item.getAttributes();
    System.out.print("     Carname : " + attributes.getNamedItem("carname"));
    System.out.println("\t type : " + attributes.getNamedItem("cartype"));
}

输出

Root element :cargalery

Current Element :garage
Garage Name : Garage1
     Carname : carname="Car4"    type : cartype="faster"
     Carname : carname="Car5"    type : cartype="faster"
     Carname : carname="Car6"    type : cartype="slower"

Current Element :garage
Garage Name : Garage2
     Carname : carname="Car1"    type : cartype="slower"
     Carname : carname="Car2"    type : cartype="faster"
     Carname : carname="Car3"    type : cartype="slower"

答案 2 :(得分:0)

您也可以尝试xpath个表达式

import java.io.ByteArrayInputStream;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpression;
import javax.xml.xpath.XPathFactory;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

public class MyXML {

    public static void main(String[] args) throws Exception {
        XPathFactory xPathfactory = XPathFactory.newInstance();
        XPath xpath = xPathfactory.newXPath();

        XPathExpression expr = xpath.compile("/cargalery/garage/cars | /cargalery/garage");
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();

        DocumentBuilder builder = factory.newDocumentBuilder();
        Document doc = builder.parse(new ByteArrayInputStream((
            "<cargalery>" +
            "<garage garagetype = \"Expensive\" garagename = \"Garage1\">"
            + "      <cars cartype=\"faster\" carname=\"Car4\"/>" +
            "        <cars cartype=\"faster\" carname=\"Car5\"/>"
            + "      <cars cartype=\"slower\" carname=\"Car6\"/>" +
            "</garage>" +
            "<garage garagetype = \"Cheap\" garagename = \"Garage2\">"
            + "      <cars cartype=\"slower\" carname=\"Car1\"/>" +
            "        <cars cartype=\"faster\" carname=\"Car2\"/>"
            + "      <cars cartype=\"slower\" carname=\"Car3\"/>" +
            "</garage>" +
            "</cargalery>").getBytes()));

        NodeList nl = (NodeList) expr.evaluate(doc, XPathConstants.NODESET);
        for (int i = 0; i < nl.getLength(); i++) {
            Node item = nl.item(i);
            if ("garage".equals(item.getNodeName())){
                System.out.println(item.getNodeName()+":"+((Element)item).getAttribute("garagename"));
            }else if ("cars".equals(item.getNodeName())) {
                System.out.println(item.getNodeName()+":"+((Element)item).getAttribute("carname"));
            }
        }
    }
}

输出

garage:Garage1
cars:Car4
cars:Car5
cars:Car6
garage:Garage2
cars:Car1
cars:Car2
cars:Car3

答案 3 :(得分:0)

你可以使用它对事件起作用的SAX解析器,它会在元素的每次会议中生成一个事件(按项目,理解所有类型的元素:开始标记,结束标记......)。这是一个例子它的用途:

public void startElement(String namespaceURI, String lname,
      String qname, Attributes attrs) throws SAXException {

   System.out.println("---------------------------------------------");
   //cette variable contient le nom du nœud qui a créé l'événement
   System.out.println("qname = " + qname);
   node = qname;

   //Cette dernière contient la liste des attributs du nœud
   if (attrs != null) {
      for (int i = 0; i < attrs.getLength(); i++) {
         //nous récupérons le nom de l'attribut
         String aname = attrs.getLocalName(i);
         //Et nous affichons sa valeur
         System.out.println("Attribut " + aname + " valeur : " + attrs.getValue(i));
      }
   }
}   

public void endElement(String uri, String localName, String qName)
      throws SAXException{
  System.out.println("Fin de l'élément " + qName);       
}

public void characters(char[] data, int start, int end){   
   System.out.println("***********************************************");
   //La variable data contient tout notre fichier.
   //Pour récupérer la valeur, nous devons nous servir des limites en paramètre
   //"start" correspond à l'indice où commence la valeur recherchée
   //"end" correspond à la longueur de la chaîne
   String str = new String(data, start, end);
   System.out.println("Donnée du nœud " + node + " : " + str);

}

这是主要的课程:

import java.io.IOException;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import javax.xml.transform.TransformerFactoryConfigurationError;
import org.w3c.dom.DOMException;
import org.xml.sax.SAXException;

public class Main {

   public static void main(String[] args) {

      try {
         SAXParserFactory factory = SAXParserFactory.newInstance();
         SAXParser parser = factory.newSAXParser();

         parser.parse("test.xml", new MyXMLHandler());

      } catch (DOMException e) {
         e.printStackTrace();
      } catch (ParserConfigurationException e) {
         e.printStackTrace();
      } catch (TransformerFactoryConfigurationError e) {
         e.printStackTrace();
      } catch (SAXException e) {
         e.printStackTrace();
      } catch (IOException e) {
         // TODO Auto-generated catch block
         e.printStackTrace();
      }
   }
}