赞和修改XML元素值

时间:2018-10-29 13:33:09

标签: java xml

我正在读取值,它可以是字符串或XML,我进行了一些修改以使其正常工作,但在解析字符串时遇到错误。下面是我编写的代码段。作为.net开发人员,我很难找到问题所在。你能帮忙吗?

我遇到错误

  

DeferredDocumentImpl错误Java dom解析器。

另一个字段值被发现为空。

DeferredDocumentImpl错误Java dom解析器

输入:

  

<account-class-desc>C & W Pensioner</account-class-desc>
<ADDRESS-PROFILE-UID>8&</ADDRESS-PROFILE-UID>

预期输出:

  

<account-class-desc>C amp; W Pensioner</account-class-desc> <ADDRESS-PROFILE-UID>8amp;</ADDRESS-PROFILE-UID>

public String getXMLParsedToHTML(String fieldValue) throws Exception {    
  String resultConvert = "";
  if (fieldValue == "") {
      return fieldValue; 
  }
  javax.xml.parsers.DocumentBuilderFactory factory = javax.xml.parsers.DocumentBuilderFactory.newInstance();
    javax.xml.parsers.DocumentBuilder builder = null;
    //making well formed xml
    InputSource is = new InputSource(new StringReader("<convert>" + fieldValue + "</convert>"));
    try
    {
        builder = factory.newDocumentBuilder();                 
        org.w3c.dom.Document doc = builder.parse(is);
        org.w3c.dom.NodeList nodeList = doc.getElementsByTagName("*");
        for (int count = 0; count < nodeList.getLength(); count++) {
            org.w3c.dom.Node node = nodeList.item(count);
            if (node.getNodeType() == org.w3c.dom.Node.ELEMENT_NODE) {
                if(!hasChildElements(node)){
                resultConvert = StringUtilities.replaceXMLStrings(node.getNodeValue());
                }else{
                    getXMLParsedToHTML(node.getNodeValue());
                }
            }
        }

    }
      catch (Exception e)
      {
          return StringUtilities.replaceXMLStrings(fieldValue);          
      }
    //removeing the 
    resultConvert.replace("<convert>", StringUtilities.EMPTY);
    resultConvert.replace("</convert>", StringUtilities.EMPTY);
    return resultConvert;

}

public boolean hasChildElements(Node el) {
    NodeList children = el.getChildNodes();
    for (int i = 0;i < children.getLength();i++) {
        if (children.item(i).getNodeType() == Node.ELEMENT_NODE) 
            return true;
        }
    return false;
    }

0 个答案:

没有答案