2015-04-04 6 views
0

Ниже мой 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. В идеале я хотел бы хранить значения всех 3 атрибутов каждый раз, когда выполняется цикл for, чтобы сохранить их в таблице базы данных. Пожалуйста, дайте мне знать, если требуется дополнительная информация.

+1

Это простое выражение XPath 2.0 производит разыскиваемых результаты - вам нужно просто понять, что в настоящее время и перевести это на Java и несколько раз оценивать выражение XPath - для каждого элемента 'industry':' //sector/industry/concat(../@sectorid, '', @id, '', @name, кодовые в строку ((10))) ' –

ответ

0

Матиас предложил правильный подход, и я придумал решение для него с небольшими изменениями:

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("C:/Users/Sachin/Desktop/SectorsAndIndustries.xml"); 
      DocumentBuilderFactory _DocumentBuilderFactory = DocumentBuilderFactory.newInstance(); 
      DocumentBuilder _DocumentBuilder = _DocumentBuilderFactory.newDocumentBuilder(); 
      Document _Document = _DocumentBuilder.parse(_XMLFile); 
      _Document.getDocumentElement().normalize(); 

      XPath _XPath = XPathFactory.newInstance().newXPath(); 

      NodeList _NodeList1 = (NodeList) _XPath.evaluate("/results/sector", _Document, XPathConstants.NODESET); 

      for (int i = 0; i < _NodeList1.getLength(); i++) { 
       Element _Element1 = (Element) _NodeList1.item(i); 

       __SectorID = Integer.parseInt(_Element1.getAttribute("sectorid")); 

       NodeList _NodeList2 = (NodeList) _XPath.evaluate("industry", _Element1, XPathConstants.NODESET); 

       for (int k=0; k < _NodeList2.getLength(); k++) { 
        __IndustryID = Integer.parseInt(_XPath.evaluate("industry[position()=" + (k + 1) + "]/@id", _Element1)); 
        __IndustryName = _XPath.evaluate("industry[position()=" + (k + 1) + "]/@name", _Element1); 

        System.out.println(__SectorID + ", " + __IndustryID + ", " + __IndustryName); 
       } 
       System.out.println("\n-----------\n"); 
      } 

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

Насколько я вижу, вы составляете список узлов с узлами, которые либо sector, либо industry элементов. Для каждого из них вы хотите получить атрибуты sectorid и id, но, очевидно, ни один элемент не имеет обоих этих атрибутов.

Лучше было бы

  • найти все sector элементов и для каждого из этой распечатки сектора ID
  • для каждого sector элемента пройти через все его дочерние элементы, называемых industry (это требует приложени второе выражение XPath к каждому элементу sector, но это тривиальное: "industry")
  • и выходной атрибут Идентификатор каждого industry
Смежные вопросы