Java에서 XML 문서의 DocType를 쉽게 변경하려면 어떻게해야합니까?

StackOverflow https://stackoverflow.com/questions/1745794

  •  20-09-2019
  •  | 
  •  

문제

내 문제는 다음과 같습니다.

내 프로그램은 XML 파일을 입력으로 가져오고 있습니다. 이 파일에는 XML 선언, DocType 선언 또는 엔티티 선언이있을 수 있지만 모두 동일한 스키마를 준수 할 수 있습니다. 내 프로그램이 새 파일을 받으면 검사하고 다음과 같은 선언이 있는지 확인해야합니다.

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE my.doctype [
<!ENTITY % entity_file SYSTEM "my.entities.ent">
%entity_file;
]>

그것이 훌륭하다면, 그것은 훌륭하고, 그대로 그대로 둘 수 있지만, 선언이 없거나 잘못된 경우, 이미있는 것을 제거하고 올바른 선언을 추가해야합니다.

이 작업을 수행 할 수있는 방법 (바람직하게는 표준 Java 6 및/또는 Apache 라이브러리를 사용하여 쉽게)?

도움이 되었습니까?

해결책

왜 "이미있는 것을 제거하고 올바른 선언을 추가해야합니까?"

입력을 위해 XML 파일을 사용하고 어떤 양식으로 작성하지 않는 경우, 적절한 솔루션은 EntityResolver.

프로세스에 대한 완전한 설명은 다음과 같습니다 여기, 그러나 다음 코드는 문서가 원하는 내용에 관계없이 파서에게 자신의 DTD를 제공하는 방법을 보여줍니다.

DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
dbf.setNamespaceAware(true);
dbf.setValidating(true);
DocumentBuilder db = dbf.newDocumentBuilder();
db.setEntityResolver(new EntityResolver()
{
    public InputSource resolveEntity(String publicId, String systemId)
        throws SAXException, IOException
    {
        return new InputSource(new StringReader(dtd));
    }
});

다른 팁

이 코드는 당신이 그것을 알아 내기 위해 시작해야합니다. DocType의 내용을 변경하려면 새 문서를 작성해야 할 수도 있습니다. 잘못된 경우 기존 내용을 수정하는 방법을 모르겠습니다.

private Document copyDocument(Document document) {
    DocumentType origDoctype = document.getDoctype();
    DocumentType doctype = documentBuilder
        .getDOMImplementation().createDocumentType(origDoctype.getName(), 
                                                   origDoctype.getPublicId(),
                                                   origDoctype.getSystemId());
    Document copiedDoc = documentBuilder.getDOMImplementation().
        createDocument(null, origDoctype.getName(), doctype);
    // so we already have the top element, and we have to handle the kids.
    Element newDocElement = copiedDoc.getDocumentElement();
    Element oldDocElement = document.getDocumentElement();
    for (Node n = oldDocElement.getFirstChild(); n != null; n = n.getNextSibling()) {
        Node newNode = copiedDoc.importNode(n, true);
        newDocElement.appendChild(newNode);
    }

    return copiedDoc;
}

해당 문서가 어떻게 형성되는지에 대한 통제력이 있다면 DTD가 불필요한 복잡성을 소개하고 스키마를 표현하는 데 소개됩니다 ...

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top