2009-12-30 2 views
1

DOM 모델에 XML 파일을로드하고 분석합니다.이스케이프 된 견적을 xml에서 이스케이프 된 견적으로 읽습니다.

해당하는 코드 :

public class MyTest { 
public static void main(String[] args) {   
    Document doc = XMLUtils.fileToDom("MyTest.xml");//Loads xml data to DOM 
    Element rootElement = doc.getDocumentElement(); 
    NodeList nodes = rootElement.getChildNodes(); 
    Node child1 = nodes.item(1); 
    Node child2 = nodes.item(3); 
    String str1 = child1.getTextContent(); 
    String str2 = child2.getTextContent();  
    if(str1 != null){ 
     System.out.println(str1.equals(str2)); 
    } 
    System.out.println(); 
    System.out.println(str1); 
    System.out.println(str2); 
} 

}

MyTest.xml

<tests> 
    <test name="1">ff1 &quot;</test> 
    <test name="2">ff1 "</test> 
</tests> 

결과 :

true 

ff1 " 
ff1 " 

원하는 결과 :

,536,
false 

ff1 &quot; 
ff1 " 

따옴표가 이스케이프 된 경우와 이스케이프되지 않은 경우를 구분해야합니다.

도와주세요.

미리 감사드립니다.

P.

public static String getRawContent(Node n) { 
    if (n == null) { 
     return null; 
    } 

    Node n1 = getChild(n, Node.TEXT_NODE); 

    if (n1 == null) { 
     return null; 
    } 

    return n1.getNodeValue(); 
} 

를 잡고 : XMLUtils # fileToDom (문자열적인 filePath), XMLUtils 클래스의 코드 조각의 코드 : 당신이 TEXT_NODE 아이를 얻고 (이 NULL이 아니다 가정) getNodeValue을 사용할 수 있습니다처럼

static { 
    DocumentBuilderFactory dFactory = DocumentBuilderFactory.newInstance(); 
    dFactory.setNamespaceAware(false); 
    dFactory.setValidating(false); 
    try { 
     docNonValidatingBuilder = dFactory.newDocumentBuilder(); 
    } catch (ParserConfigurationException e) { 
    } 
} 

public static DocumentBuilder getNonValidatingBuilder() { 
    return docNonValidatingBuilder; 
} 

public static Document fileToDom(String filePath) { 

    Document doc = getNonValidatingBuilder().newDocument(); 
    File f = new File(filePath); 
    if(!f.exists()) 
     return doc; 

    try { 
     Transformer transformer = TransformerFactory.newInstance().newTransformer(); 
     DOMResult result = new DOMResult(doc); 
     StreamSource source = new StreamSource(f); 
     transformer.transform(source, result); 
    } catch (Exception e) { 
     return doc; 
    } 

    return doc; 

} 
+1

당신이 만약 왜 이걸 필요로하니? 이 코드는 XML 문서에 맞도록 인코딩되었으며 원래 데이터에 속하지 않습니다 (& ") –

+0

http://stackoverflow.com/questions/1777878/is-there-a-java- xml-api-that-can-parse-a-document-without-resolving-character-ent/1778304 # 1778304 도움이 될만한 질문이 있습니다. – skaffman

답변

1

저는 아파치 xerces의 소스 코드를 살펴보고 내 솔루션을 제안했습니다 (하지만 원숭이 패치입니다). 나는 간단한 클래스

당신은 전에

System.setProperty(
      "org.apache.xerces.xni.parser.XMLParserConfiguration", 
      "a.MyConfig"); 

를 파싱 시작하고 결과를 예상 할 것이다 당신의 주요 방법 만 다음 줄을 추가해야

package a; 
import java.io.IOException; 
import org.apache.xerces.impl.XMLDocumentScannerImpl; 
import org.apache.xerces.parsers.NonValidatingConfiguration; 
import org.apache.xerces.xni.XMLString; 
import org.apache.xerces.xni.XNIException; 
import org.apache.xerces.xni.parser.XMLComponent; 

public class MyConfig extends NonValidatingConfiguration { 

    private MyScanner myScanner; 

    @Override 
    @SuppressWarnings("unchecked") 
    protected void configurePipeline() { 
     if (myScanner == null) { 
      myScanner = new MyScanner(); 
      addComponent((XMLComponent) myScanner); 
     } 
     super.fProperties.put(DOCUMENT_SCANNER, myScanner); 
     super.fScanner = myScanner; 
     super.fScanner.setDocumentHandler(this.fDocumentHandler); 
     super.fLastComponent = fScanner; 
    } 

    private static class MyScanner extends XMLDocumentScannerImpl { 

     @Override 
     protected void scanEntityReference() throws IOException, XNIException { 
      // name 
      String name = super.fEntityScanner.scanName(); 
      if (name == null) { 
       reportFatalError("NameRequiredInReference", null); 
       return; 
      } 

      super.fDocumentHandler.characters(new XMLString(("&" + name + ";") 
       .toCharArray(), 0, name.length() + 2), null); 

      // end 
      if (!super.fEntityScanner.skipChar(';')) { 
       reportFatalError("SemicolonRequiredInReference", 
         new Object[] { name }); 
      } 
      fMarkupDepth--; 
     } 
    } 

} 

작성했습니다

false 

ff1 &quot; 
ff1 " 
0

내부 실체를 위해 이것을하는 아무 방법도 없다. XML은이 개념을 지원하지 않습니다. 내부 엔티티는 텍스트에 동일한 PSVI 컨텐츠를 작성하는 다른 방법 일뿐 아니라 고유하지 않습니다.

관련 문제