在JAVA中解析XML,抽出一段特定的数据

问题描述:

我不知道如何准确地提出我的问题。我相信有两个问题可以帮助:在JAVA中解析XML,抽出一段特定的数据

我一直在玩解析文件 - 特别是XML。

我发现了很多教程和许多技巧。

大多数教程都有一个简单的xml文件,首先包含姓名,电话号码等等。

我的2个问题:

1)如何可以提取/显示只是一个特定之间的数据。例如,如果我只是想显示<FirstNames>我该怎么做(在Java中)如下:

loop 

If <tag> = “FirstName” then name_variable = data in between tags); 

or 

If <tag> = “FirstName” then System.out.printf(“ the first name is %s\n”,name_variable); 

end loop 

2)假设我要找只有名字的第二个实例,在一些教程/例子我已经看到如何显示循环内的所有数据。我曾尝试将数据设置为“排列”字符串,然后在循环外部显示数据但已被删除。底线,你如何存储一个索引(数组)的分析XML数据以供后续代码使用或传递?

<company> 
<Name>My Company</Name> 
<Executive type = "CEO"> 
    <LastName>Smith</LastName> 
    <FirstName>Jim</FirstName> 
    <street>123 Main Street</street> 
    <city>Mytown</city> 
    <state>TN</state> 
    <zip>11234</zip> 
</Executive> 
<Executive type = "OEC"> 
    <LastName>Jones</LastName> 
    <FirstName>John</FirstName> 
    <street>456 Main Street</street> 
    <city>Gotham</city> 
    <state>TN</state> 
    <zip>11234</zip> 
</Executive> 
</company> 

下面是一些代码,我拼凑起来,我正在从我的XML的一些数据,但我还没有想出如何在索引块解析数据的存储。

package dom_parsing_in_java; 
import org.w3c.dom.*; 
import javax.xml.parsers.*; 
import java.io.*; 
import org.w3c.dom.NodeList; 
import org.w3c.dom.Node; 
import org.w3c.dom.NamedNodeMap; 
//import com.sun.org.apache.xerces.internal.parsers.DOMParser; 

public class DOM_Parsing_In_JAVA { 

    public static void main(String[] args) { 
    // TODO code application logic here 
    String file = "test2.xml"; 

if(args.length >0){ 
    file = args[0]; 

}// end If 

try{ 
    //DOMParser parser= new DOMParser(); 
    DocumentBuilderFactory factory= DocumentBuilderFactory.newInstance(); 
    DocumentBuilder builder = factory.newDocumentBuilder(); 
    Document document = builder.parse(new File(file)); 

    //Document document = parser.getDocument(); 

    Element root = document.getDocumentElement(); 
    System.out.println(root.getTagName()); 

    NodeList node_list = root.getElementsByTagName("Executive"); 


    //Node comp = getNode("Company",root); 

    int i; 


    for(i = 0; i<node_list.getLength();i++){ 
     Element department = (Element)node_list.item(i); 

     System.out.println(department.getTagName()); 
     System.out.println("name "+document.getElementsByTagName("Name").item(0).getTextContent()); 
     System.out.println("name "+document.getElementsByTagName("FirstName").item(i).getTextContent()); 
     System.out.printf(" Lastname: %s%n ", document.getElementsByTagName("LastName").item(i)); 
     System.out.printf(" Lastname: %s%n ", department.getAttribute("LastName")); 
     System.out.printf(" FirstName: %s%n",department.getAttribute("FirstName")); 
     //System.out.printf(" elements by Tag %s%n",department.getElementsByTagName("testTag")); 
     //System.out.printf(" staff: %s%n",countStaff(department)); 
    } 

} 
catch(Exception e){ 
    e.printStackTrace(); 

}//end catch 
} 
} 

+0

我昨晚(昨晚太晚)因试图通过StAX示例并阅读一些内容而感到沮丧。 昨晚有一种体面的挫折感。我一直在网上搜索关于在JAVA中解析XML的指示。我认为我的最终目标非常简单 - 提取并在变量中存储特定的“标记”XML数据片段并在其他地方使用它。 上周我得到了真正的使用DOM关闭,但无法获取数据存储并传递给另一部分。我可以展示它,感觉就像我差不多在那里。 我可以使用一些额外的建议和方向。 – user638361 2013-02-27 14:14:49

+0

我阅读并通过上述链接工作。我感觉像http://docs.oracle.com/javase/tutorial/jaxp/stax/example中提到的示例。html#bnbfz 假设一定程度的JAVA熟练程度 - 看起来这些示例给出了snip-它的部分代码段,其余的代码应该是明显的。 我可以使用一些额外的建议和方向。谢谢! – user638361 2013-02-27 14:15:38

我会走下XPath路线并将XML文件解析为文档。

XPath可用于导航XML文档。请参阅http://www.w3schools.com/xpath/default.asp了解有关使用XPath可以实现的功能的更多信息。

假设一切都在主做:

public static void main(String[] args) { 
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); 
    DocumentBuilder builder = factory.newDocumentBuilder(); 
    Document doc = builder.parse(new File("file.xml")); 
    XPathFactory xPathfactory = XPathFactory.newInstance(); 
    XPath xpath = xPathfactory.newXPath(); 
    XPathExpression firstnameExpr = xpath.compile("//FirstName"); 

    NodeList nl = (NodeList) firstnameExpr.evaluate(doc, XPathConstants.NODESET); 

    for (int i=0; i<nl.getLength(); i++) { 
     Node node = nl.item(i); 

     // this is assuming the first child of Firstname is the characters (contents) 
     // of the Firstname tag, you may need to do some checking whether or not 
     // node.getNodeType() == Node.Text; 
     System.out.println("Firstname["+i+"] = " 
           + node.getChildNodes()[0].getTextContent()); 
    } 


} 

而不是打印头名的内容到System.out你可以在添加值的ArrayList这将维持秩序,即:

List<String> firstnameList = new ArrayList<String>(); 

for (int i=0; i<nl.getLength(); i++) { 
    Node node = nl.item(i); 

    // again, you might want to check that .getChildNodes() doesn't return null 
    // and that it is of type Node.Text 
    firstnameList.add(node.getChildNodes()[0].getTextContent()); 
}