以下是我的XML文件:從父和子節點的XPath選擇屬性值
<?xml version="1.0" encoding="UTF-8"?>
<query xmlns:yahoo="http://www.yahooapis.com/v1/base.rng" yahoo:lang="en-GB">
<results>
<sector sectorid="1" sectorname="Basic Materials">
<industry id="112" name="Agricultural Chemicals"/>
<industry id="132" name="Aluminum"/>
<industry id="110" name="Chemicals - Major Diversified"/>
<industry id="131" name="Copper"/>
<industry id="134" name="Gold"/>
<industry id="121" name="Independent Oil and Gas"/>
<industry id="120" name="Major Integrated Oil and Gas"/>
</sector>
<sector sectorid="2" sectorname="Conglomerates">
<industry id="210" name="Conglomerates"/>
</sector>
<sector sectorid="7" sectorname="Services">
<industry id="720" name="Advertising Agencies"/>
<industry id="773" name="Air Delivery and Freight Services"/>
<industry id="772" name="Air Services and Others"/>
<industry id="730" name="Apparel Stores"/>
<industry id="744" name="Auto Dealerships"/>
</sector>
</results>
</query>
從上面的XML文件,我要找存儲屬性的值:sectorid
,id
,並在適當的name
變量(我正在使用Java)。我一直在尋找不同的XPath表達式,並且提出了以下代碼,但是,當存儲值id
屬性時,會引發java.lang.NumberFormatException: For input string: ""
異常。這裏是我的代碼:
public class XMLToDatabase {
private static int __SectorID;
private static int __IndustryID;
private static String __IndustryName;
public static void main(String[] args) throws SQLException, UnsupportedEncodingException, ParserConfigurationException, SAXException, IOException, XPathExpressionException {
try {
File _XMLFile = new File("SectorsAndIndustries.xml");
DocumentBuilderFactory _DocumentBuilderFactory = DocumentBuilderFactory.newInstance();
_DocumentBuilderFactory.setNamespaceAware(true);
DocumentBuilder _DocumentBuilder = _DocumentBuilderFactory.newDocumentBuilder();
Document _Document = _DocumentBuilder.parse(_XMLFile);
_Document.getDocumentElement().normalize();
XPath _XPath = XPathFactory.newInstance().newXPath();
XPathExpression _XPathExpression = _XPath.compile("//sector | //industry");
NodeList _NodeList = (NodeList) _XPathExpression.evaluate(_Document, XPathConstants.NODESET);
for (int i = 0; i < _NodeList.getLength(); i++) {
Node _Node = _NodeList.item(i);
if(_Node.getNodeType() == Node.ELEMENT_NODE) {
Element _Element = (Element) _Node;
__SectorID = Integer.parseInt(_Element.getAttribute("sectorid"));
__IndustryID = Integer.parseInt(_Element.getAttribute("id"));
__IndustryName = _Element.getAttribute("name");
}
System.out.println(__SectorID + ", " + __IndustryID + ", " + __IndustryName);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
可能有人請幫助我確定它是否是XPath Expression
,我犯了一個錯誤使用,或者如果路上我儲存的第二個變量__IndustryID
?因爲第一個變量__SectorID
正確存儲值1
,但引發上述__IndustryID
的異常。理想情況下,每次執行for
循環時,我都希望存儲所有3個屬性的值,以將它們保存到數據庫表中。請讓我知道是否需要更多信息。
這個簡單的XPath 2.0表達式產生想要的結果 - 你只需要明白的是什麼完成並將其轉換爲Java並對XPath表達式進行多次評估 - 對於每個'industry'元素:'//sector/industry/concat(../@sectorid,'',@id,'',@name,碼點到字符串((10)))' – 2015-04-05 00:54:21