Blackberry:如何在解析XML时获取Node的原始内容

时间:2013-01-02 20:06:44

标签: xml blackberry java-me

我试图从通过SOAP Web服务调用返回的某些XML中提取html字符串。我的Node对象属于以下类:

org.w3c.dom.Node

以下是我用于遍历节点的循环的代码示例:

for(int t = 0; t < elements; t++)
{

         Element myElement = (Element)elements.item(t);

         NodeList childNodes = myElement.getChildNodes();
         int numChildren = childNodes.getLength();

         for(int counter = 0; counter < numChildren; counter++)
         {
             Node currentNode = childNodes.item(counter);
             NodeList currentNodeChildNodes = currentNode.getChildNodes();

             int numCurrentNodeChildren = currentNodeChildNodes.getLength();
             Node firstChild = currentNodeChildNodes.item( 0 );
         }
}

现在,其中一些节点包含原始html。这当然让他们看起来像有孩子。我想把这些html节点直接放到String中。我尝试了currentNode.getTextContent(),只生成java.lang.NullPointerException

我是否可以使用一种方法来获取节点并将其原始内容作为String获取,无论它是否包含子节点?

编辑:以下是带有html内容的XML的示例

<?xml version="1.0" encoding="utf-16"?>
<soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
      xmlns:xsd="http://www.w3.org/2001/XMLSchema"
      xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
  <soap:Body>
    <GetInfoResponse xmlns="http://www.mycompany.com/">
      <GetInfoResult>
        <infoList>
          <Info>
            <iso>US</iso>
            <country_name>United States</country_name>
            <title>This is the title</title>
            <html_string><strong>NEWS</strong><h1>This is a section header</h1><p>Here is some information</p></html_string>
            <last_update_date>2013-01-01 00:00:00</last_update_date>
          </Info>
        </infoList>
        <faultResponse>
          <faultOccurred>boolean</faultOccurred>
          <faultDescription>string</faultDescription>
        </faultResponse>
      </GetInfoResult>
    </GetInfoResponse>
  </soap:Body>
</soap:Envelope>

1 个答案:

答案 0 :(得分:2)

混合html和xml内容通常是一个坏主意。虽然html 可以格式化为xml(xhtml),但它往往不是。通过混合这两者,当你的html不是有效的xml时,你冒着导致xml解析失败的风险。相反,您应该将您的html内容编码为有效的xml元素值。如果你这样做,那么你可以使用Node.getTextContent()元素上的html_string调用来获取java中的数据。