Entity Declaration missing when updating XML Files - Java

247 Views Asked by At
<!DOCTYPE extended-info [
    <!ENTITY product-info SYSTEM "${product.info}">
    <!ENTITY item-info SYSTEM "${item.info}">
]>
<root-element>
    <element>
    </element>
    ....
    &product-info;
    &item-info;
</root-element>

I have an XML like the above one.

I'm using the below code to parse the XML and update attributes.

DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
docBuilder.setEntityResolver(new EntityResolver(){
    public InputSource resolveEntity (String publicId, String systemId)
    {
        try
        {
            return new InputSource(new StringReader(""));
        }
        catch(Exception e)
        {
            e.printStackTrace();
        }
        return null;
    }
});

Document doc = docBuilder.parse(new java.io.FileInputStream(xml_path));
NodeList attributes = doc.getElementsByTagName("configuration");
for(int i=0;i<attributes.getLength();i++) {
    Element ele = (Element)attributes.item(i);
    String attributeName = ele.getAttribute("name");//No I18N
    if("ElementName".equals(attributeName)) {
        ele.setAttribute("value",newElementValue);
    }
}

Transformer transformer = TransformerFactory.newInstance().newTransformer();
transformer.setOutputProperty(OutputKeys.INDENT, "yes");//No I18N
StreamResult result = new StreamResult(new File(xml_path));
DOMSource source = new DOMSource(doc);
transformer.transform(source, result);

I'm using DOM Parser to parse the XML File and update the content using a Transformer in Java.

When updating the XML file, the DOCTYPE and &product-info; and &item-info; are removed.

How do I retain the values using Java and not any third-party libraries?

0

There are 0 best solutions below