Java에서 익숙하지 않으며 XML 조작에 문제가 있습니다.Java에서 여러 XML 문서 구문 분석
Assistant Type Bonus
Assistant BonusRateHourlyRate 10
Assistant EffectiveDate 01/1/1753
Assistant ExpirationDate 01/1/3000
Assistant SimpleValue 2204
Assistant SimpleValue 2206
: 궁극적으로 내가 규칙 이름을 추출하고 그와 관련된 모든 속성이의 출력을 만들 달성하는 것입니다 필요
<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>
:
이 XML 조각을 고려구조가 다른 수백 개의 XML 파일을 전달해야하므로 각 문서와 cre를 반복 할 수있는 재사용 가능한 코드를 만들려고했습니다. 형식에 관계없이이 출력을 먹었습니다. 일관성있는 한 가지는 이름 (출력의 열 1)이 항상 Name = "xxx"의 형식 일 것입니다.
다음 코드는 위의 샘플 XML에 나를 가까이 가져하지만 몇 가지 문제가 있습니다 그것을 다른 문서
는 두 번째의 취득에 실패에 걸쳐 재사용되지 않도록
- 그것은 하드 XPath의이 필요를
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);
2206 SimpleValue 나는 누군가가 올바른 방향으로 날 가리거나 좀 사를 줄 수있는 기대했다 그 결과를 얻는 데 도움이 될 수있는 mple 코드입니다.