How to get cdata value from xml in java | How to read cdata in xml using java
In this article, we are going to discuss XML CDATA which stands for Character Data. which is defined as blocks of text that will not be parsed by the xml parser.
syntax of cdata in xml:
<![CDATA[
characters with markup
]]>
Java provides some of the options to parse XML documents. Some of the commonly used XML parsers for java programming language are as follows:
- DOM Parser (Document Object Model)
- SAX Parser
- StAX Parser (Streaming API for XML)
- JAXB
let us consider the following xml file cdata.xml
cdata.xml
<?xml version="1.0" encoding="UTF-8"?>
<employee>
<emp_info id="1">
<emp_name>
<first_name>abc</first_name>
<last_name>xyz</last_name>
</emp_name>
<emp_contact_info>
<address><![CDATA[
This is the CDATA area.
You can store special character that are recognize. Ex. ' " & / - < >
you can specify company address also
]]>
</address>
</emp_contact_info>
</emp_info>
</employee>
This is the java program.
XmlCData.java
import java.io.File;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.CharacterData;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
class XmlCData{
public static String getCharacterDataFromElement(Element e) {
NodeList list = e.getChildNodes();
String data;
for(int index = 0; index < list.getLength(); index++){
if(list.item(index) instanceof CharacterData){
CharacterData child = (CharacterData) list.item(index);
data = child.getData();
if(data != null && data.trim().length() > 0)
return child.getData();
}
}
return "";
}
}
JavaXmlCdata .java
public class JavaXmlCdata {
public static void main(String[] args) throws Exception{
File file = new File("D:\\cdata.xml");
DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
Document doc = builder.parse(file);
NodeList nodes = doc.getElementsByTagName("emp_contact_info");
for (int i = 0; i < nodes.getLength(); i++) {
Element element = (Element) nodes.item(i);
NodeList title = element.getElementsByTagName("address");
Element line = (Element) title.item(0);
System.out.println("Cdata is " + XmlCData.getCharacterDataFromElement(line));
}
}
}
No comments:
Post a Comment