Будучи неопытным в Java и манипулирование XML, я застрял в проблеме.Анализ нескольких XML-документов в Java
Рассмотрим XML фрагмент:
<Rule Name="Assistant">
<RuleVersions>
<Adjustments>
<Adjustment Type="Bonus" BonusRateHourlyRate="10"></Adjustment>
</Adjustments>
<RuleVersion EffectiveDate="01/1/1753" ExpirationDate="01/1/3000">
<Triggers>
<SimpleValue Value="2204"/>
<SimpleValue Value="2206"/>
</Triggers>
</RuleVersion>
</RuleVersions>
В конце концов, что мне нужно, чтобы достичь это, чтобы извлечь имя правила, а затем каждый атрибут, связанный с ним, чтобы создать выход этого:
Assistant Type Bonus
Assistant BonusRateHourlyRate 10
Assistant EffectiveDate 01/1/1753
Assistant ExpirationDate 01/1/3000
Assistant SimpleValue 2204
Assistant SimpleValue 2206
Поскольку мне нужно передать сотни XML-файлов, все с разными структурами, я стремился создать многократно используемый код, который мог бы просто перебирать каждый документ и создавать ели этот выход, независимо от его формата. Единственное, что согласуется с тем, что Имя (столбец 1 вывода) всегда будет в формате Name = "xxx".
Следующий код заставляет меня близко на приведенном выше примере XML, но есть несколько вопросов:
- Это требует жестко закодированные XPaths поэтому не может повторно использоваться в различных документах
он не может получить второе SimpleValue 2206
FileInputStream file = new FileInputStream(new File("Output\\XML\\Test.xml")); DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = builderFactory.newDocumentBuilder(); Document xmlDocument = builder.parse(file); XPath xPath = XPathFactory.newInstance().newXPath(); String TestCase = ""; String name = "Rule/@Name"; NodeList nodeList = (NodeList) xPath.compile(name).evaluate(xmlDocument, XPathConstants.NODESET); NodeList Type = (NodeList) xPath.compile("Rule/RuleVersions/Adjustments/Adjustment/@Type").evaluate(xmlDocument, XPathConstants.NODESET); NodeList BonusRateHourlyRate = (NodeList) xPath.compile("Rule/RuleVersions/Adjustments/Adjustment/@BonusRateHourlyRate").evaluate(xmlDocument, XPathConstants.NODESET); NodeList EffectiveDate = (NodeList) xPath.compile("Rule/RuleVersions/RuleVersion/@EffectiveDate").evaluate(xmlDocument, XPathConstants.NODESET); NodeList ExpirationDate = (NodeList) xPath.compile("Rule/RuleVersions/RuleVersion/@ExpirationDate").evaluate(xmlDocument, XPathConstants.NODESET); NodeList SimpleValue = (NodeList) xPath.compile("Rule/RuleVersions/RuleVersion/Triggers/SimpleValue/@Value").evaluate(xmlDocument, XPathConstants.NODESET); //Build the test cases file for (int i = 0; i < nodeList.getLength(); i++) { TestCase = TestCase + nodeList.item(i).getFirstChild().getNodeValue() + " Type " + Type.item(i).getNodeValue() + "\n"; TestCase = TestCase + nodeList.item(i).getFirstChild().getNodeValue() + " BonusRateHourlyRate " + BonusRateHourlyRate.item(i).getNodeValue() + "\n"; TestCase = TestCase + nodeList.item(i).getFirstChild().getNodeValue() + " EffectiveDate " + EffectiveDate.item(i).getNodeValue() + "\n"; TestCase = TestCase + nodeList.item(i).getFirstChild().getNodeValue() + " ExpirationDate " + ExpirationDate.item(i).getNodeValue() + "\n"; TestCase = TestCase + nodeList.item(i).getFirstChild().getNodeValue() + " SimpleValue " + SimpleValue.item(i).getNodeValue() + "\n"; } System.out.println(TestCase);
Я надеялся, что кто-то может мне точку в правильном направлении или дать мне некоторые са который может помочь мне достичь результата, который я получаю после.