解释自己的最佳方式是向您展示一段代码:
这是我正在解析的 XML 文件:
<module>
<name>name1</name>
<type>type</type>
<content>
<p>This is some piece of code that should be treated as a full string, even that 'p' tag, because I want to use all content inside p tag for a webview in android.
</p>
<h1>This is a big classy title in html</h1>
</content>
</module>
正如您在p
标签中看到的那样,基本上我想获取<content>
标签的内容并将其保存到要处理的字符串中。所以最后,我想初始化一个字符串,如下所示:
String content = "<p> This is some piece.......</p> <h1>This is....</h1>";
这是我用来获取值<name>
的代码:<type>
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
Document doc = dBuilder.parse(contingut);
doc.getDocumentElement().normalize();
NodeList nodes = doc.getElementsByTagName("module");
for (int i = 0; i < nodes.getLength(); i++) {
Node node = nodes.item(i);
Element element = (Element) node;
if(element.getNodeType() == Element.ELEMENT_NODE){
System.out.println(getValue("name",element));
System.out.println(getContent("content",element));
}
}
private static String getValue(String tag, Element element) {
String value="";
try {
NodeList nodes = element.getElementsByTagName(tag).item(0).getChildNodes();
Node node = (Node) nodes.item(0);
value=node.getNodeValue();
} catch (Exception e){
value=null;
}
return value;
}
因此,例如,在解析时,名称打印正确name1
,但content
返回空白。
知道如何将<content>
内容作为字符串获取吗?
谢谢你。
编辑
private static String getContent(String tag, Element element) {
String value="";
try {
Node nodes = element.getElementsByTagName(tag).item(0);
value = nodes.getTextContent();
} catch (Exception e){
value=null;
}
return value;
}
Log.d("debugging",getContent("content",element));
这是打印这个:
%20%20%20%20%20This%20some%20piece ....
似乎它没有返回 string <p>
。