Search code examples
javaxmlliferaysax

Parse and update liferay web content


I have a JournalArticle web content with the following section.

<root available-locales="en_GB" default-locale="en_GB">
    <dynamic-element name="image-id" type="text" index-type="keyword" index="0">
        <dynamic-content language-id="en_GB">
            <![CDATA[ENG_ID1]]>
        </dynamic-content>
    </dynamic-element>
    <dynamic-element name="main-picture" type="document_library" index-type="keyword" index="0">
        <dynamic-element name="main-picture-url" index="0" type="text" index-type="keyword">
            <dynamic-content language-id="en_GB">
                <![CDATA[http://localhost:8080/documents/11111/22222/Image1/c9ff3112-22a1-4a45-a5d7-ea0b687fa34f?t=1450349423000]]>
            </dynamic-content>
        </dynamic-element>
        <dynamic-content language-id="en_GB">
            <![CDATA[/documents/11111/22222/Image2/c9ff3113-23a1-4a35-a1d7-ea0b127fa34f?t=1450349423000]]>
        </dynamic-content>
    </dynamic-element>
</root>

I was trying to parse through the xml and update the url inside main-picture-url with the one in the below dynamic-content if value NotEmpty.

String HOST = "localhost";
String PORT = "8080";
Document contentDocument = SAXReaderUtil.read(content);

List<String> elementNames = Arrays.asList("main-picture");
for (String elementName : elementNames) {
    Node mainNode = contentDocument.selectSingleNode("/root/dynamic-element[@name='"+elementName+"']/dynamic-content");
    Node urlNode = contentDocument.selectSingleNode("/root/dynamic-element[@name='"+elementName+"']/dynamic-element/dynamic-content");

    Integer urlNodeIndex = contentDocument.indexOf(urlNode);
    String mainValue = mainNode.getText();
    if(!mainValue.equalsIgnoreCase("")) {
        urlNode.setText("http://"+HOST+":"+PORT+mainValue);

        System.out.println("urlValue is ---> "+urlNode.getText());
    }
}

As you can see above, I can extract the value and set it to the urlNode. But I am totally confused how to set this urlNode back to the content. I couldn't find any method in SAXReaderUtil helping me to update the content.

Is there any way by which I can UPDATE the content?


Solution

  • The answer was straightforward. I just had to do

    content = contentDocument.asXML()
    

    to set back the updated document back as content.