2014-10-24 4 views
0

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에 나를 가까이 가져하지만 몇 가지 문제가 있습니다 그것을 다른 문서

  • 는 두 번째의 취득에 실패에 걸쳐 재사용되지 않도록

    1. 그것은 하드 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 코드입니다.

  • 답변

    0

    지금 업데이트 된 답변을 참조하십시오. 모든 속성과 값을 읽으려고했습니다. 당신은 this 웹 사이트에서 얻을 sax2r2.jar 파일을 다운로드해야합니다.

    import java.util.HashMap; 
    import javax.xml.parsers.SAXParser; 
    import javax.xml.parsers.SAXParserFactory; 
    import org.xml.sax.Attributes; 
    import org.xml.sax.helpers.DefaultHandler; 
    
    public class NewClass extends DefaultHandler { 
    
        public static void main(String[] args) { 
    
         try { 
          SAXParserFactory saxParserFactory = SAXParserFactory.newInstance(); 
          SAXParser saxParser = saxParserFactory.newSAXParser(); 
          HashMap<String, String> map = new HashMap(); 
          String adjustment,ruleVersion,simpleValue; 
    
          DefaultHandler defaultHandler = new DefaultHandler() { 
           @Override 
           public void startElement(String uri, String localName, String qname, Attributes attributes) { 
            if(attributes.getLength()>0) 
            { 
             int items = attributes.getLength(); 
             System.out.println("Qualified Name:"+qname); 
             for(int i=0;i<items;i++) 
              System.out.println(attributes.getQName(i)+":"+attributes.getValue(i)); 
            } 
    
           } 
          }; 
          saxParser.parse("e:\\abc.xml", defaultHandler); 
         } catch (Exception e) { 
          e.printStackTrace(); 
         } 
        } 
    } 
    
    0

    내가이 나는 또한 내가 필요하지 않은 몇 가지 추가 조각을 떼어 내고이 코드를 사용하여 필요한대로 작업을 한 것 같은데, 각 라인의 시작 부분에 이름을 추가합니다

    try { 
         SAXParserFactory saxParserFactory = SAXParserFactory.newInstance(); 
         SAXParser saxParser = saxParserFactory.newSAXParser(); 
         DefaultHandler defaultHandler = new DefaultHandler() { 
          String ruleName = null; 
          public void startElement(String uri, String localName, String qname, Attributes attributes) { 
    
           if (attributes.getLength() > 0) { 
            int items = attributes.getLength(); 
            for (int i = 0; i < items; i++) { 
             if ((qname.toString().equals("Header")) || (qname.toString().equals("Response"))) { 
              //Dont print out the XML headers 
             } else { 
              if (attributes.getQName(i).equals("Name")) { 
               ruleName = attributes.getValue(i); 
              } else { 
               //Don't reset the string; 
              } 
              System.out.println(ruleName+":"+qname + ":" + attributes.getQName(i) + ":" + attributes.getValue(i)); 
             } 
            } 
           } 
          } 
         }; 
         saxParser.parse(
           "Test.xml", defaultHandler); 
        } catch (Exception e) { 
         e.printStackTrace(); 
        } 
    
    0

    이와 같은 문제에 대해 저수준 Java 코드를 작성하고 싶지는 않습니다. XSLT 또는 XQuery에서 훨씬 더 효과적입니다.

    다른 요소를 다르게 처리하기 때문에 예제 출력을 완전히 일반적으로 수행 할 수 없습니다. 예를 들어 Adjustment/@ Type을 사용하여 특성 이름을 출력하지만 SimpleValue/@ Value를 사용하면 요소 이름을 출력 할 수 있습니다. 그것이 감독이라고 가정 해 봅시다. 그런 다음이 XSLT 규칙을 통해 원하는 것을 얻을 수 있습니다.

    <xsl:template match="Rule//@*"> 
        <xsl:value-of select="concat(ancestor::Rule/@Name, ' ', name(), ' ', .)"/> 
    </xsl:template> 
    

    Java 코드를 작성하는 데는 많은 시간이 걸립니다.