[英]Accessing parameters from XML file in java
我有一個庫存記錄XML文件來存儲每個項目的數量。
<Inventory>
<Item>
<ManufacturerName>Brand1</ManufacturerName>
<ProductType>TV</ProductType>
<Quantity>146</Quantity>
</Item>
<Item>
<ManufacturerName>Brand2</ManufacturerName>
<ProductType>TV</ProductType>
<Quantity>221</Quantity>
</Item>
<Item>
<ManufacturerName>Brand3</ManufacturerName>
<ProductType>TV</ProductType>
<Quantity>36</Quantity>
</Item>
</Inventory>
在我的Java程序中,如果收到對某個項目的請求,則會檢查剩余該類型的項目數量(“數量”參數),如果足夠,請從XML文件中減去該數量。 我可以通過遍歷XML的每個節點並檢查所需的節點來做到這一點,但是我希望有一種更快的方法可以立即訪問一個特定的節點。 也許可以更改XML文件的結構以使其更易於訪問,但我想不到一個。
您正在尋找的是XPath,這是一個小樣本:
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.NodeList;
public class GetAllTheChildren {
public static void main(String[] args) {
try{
DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
documentBuilderFactory.setNamespaceAware(true);
DocumentBuilder builder = documentBuilderFactory.newDocumentBuilder();
Document doc = builder.parse("/home/eugen/Desktop/input.txt");
XPathFactory xPathFactory = XPathFactory.newInstance();
XPath xpath = xPathFactory.newXPath();
XPathExpression expression = xpath.compile("/Inventory/Item[Quantity>200]/*");
NodeList nodes = (NodeList) expression.evaluate(doc, XPathConstants.NODESET);
for(int i = 0;i<nodes.getLength();i++){
System.out.println(nodes.item(i).getNodeName());
System.out.println(nodes.item(i).getTextContent());
}
} catch(Exception exception){
exception.printStackTrace();
}
}
}
您可能需要多玩一些
干杯,尤金。
用Java處理XML的方法有很多。 例如,您可能需要研究Castor 。 使用Castor,您可以將XML“加載”到Java類中,在Java中進行更改,然后將其轉換回XML。
DOM4J(開源XML解析器http://dom4j.sourceforge.net/ )非常合適。
您可以調用Element.elements()方法來獲取其子節點的總數。 使用Element.element(String name)獲取具有該名稱的特定節點。 請參閱此API文檔: http : //dom4j.sourceforge.net/dom4j-1.6.1/apidocs/org/dom4j/Element.html#element%28java.lang.String%29
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.