我以前從未處理過XML,所以我不確定如何在XML文件中處理CDATA.我迷失在節(jié)點,父節(jié)點,子節(jié)點,nList等中.
誰能告訴我這些代碼片段的問題是什么?
我的getTagValue()方法適用于除“詳細信息”之外的所有標記,“詳細信息”是包含CDATA的標記.
.....
NodeList nList = doc.getElementsByTagName("Assignment");
for (int temp = 0; temp < nList.getLength(); temp ) {
Node nNode = nList.item(temp);
if (nNode.getNodeType() == Node.ELEMENT_NODE) {
Element eElement = (Element) nNode;
results = ("Class : " getTagValue("ClassName", eElement))
("Period : " getTagValue("Period", eElement))
("Assignment : " getTagValue("Details", eElement));
myAssignments.add(results);
}
}
.....
private String getTagValue(String sTag, Element eElement) {
NodeList nlList = eElement.getElementsByTagName(sTag).item(0).getChildNodes();
Node nValue = (Node) nlList.item(0);
if((CharacterData)nValue instanceof CharacterData)
{
return ((CharacterData) nValue).getData();
}
return nValue.getNodeValue();
}
解決方法: 我懷疑你的問題出在getTagValue方法的以下代碼行中:
Node nValue = (Node) nlList.item(0);
你總是得到第一個孩子!但是你可能不止一個.
以下示例有3個子節(jié)點:文本節(jié)點“detail”,CDATA節(jié)點“with cdata”和文本節(jié)點“here”:
<Details>detail <![CDATA[with cdata]]> here</Details>
如果你運行你的代碼,你只得到“細節(jié)”,你就會失去其余部分.
以下示例有1個子節(jié)點:CDATA節(jié)點“此處帶有cdata的詳細信息”:
<Details><![CDATA[detail with cdata here]]></Details>
如果你運行你的代碼,你會得到一切.
但是上面這樣寫的例子如下:
<Details>
<![CDATA[detail with cdata here]]>
</Details>
現(xiàn)在有3個孩子因為空格和換行被選為文本節(jié)點.如果您運行代碼,則會獲得帶有換行符的第一個空文本節(jié)點,其余部分將丟失.
您要么遍歷所有子項(無論多少)并連接每個子項的值以獲得完整結(jié)果,或者如果區(qū)分純文本和CDATA內(nèi)的文本并不重要,則在上面設置合并屬性文檔制作工廠首先:
DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
docFactory.setCoalescing(true);
...
Coalescing specifies that the parser produced by this code will convert CDATA nodes to Text nodes and append it to the adjacent (if any) text node. By default the value of this is set to false. 來源:https://www./content-1-434451.html
|