将html标记存储在xml中 [英] Store html tags in xml

查看:38
本文介绍了将html标记存储在xml中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个具有html格式和各种html标签的字符串.我想将此字符串放在xml标记中,以便html标记保留.例如

I have a String having html format with various html tags. I want to put this string in xml tags such that the html tags stay. e.g.

public class XMLfunctions {

    public final static Document XMLfromString(String xml){

        Document doc = null;

        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
                try {

            DocumentBuilder db = dbf.newDocumentBuilder();

            InputSource is = new InputSource();
            is.setCharacterStream(new StringReader(xml));
            doc = db.parse(is); 

        } catch (ParserConfigurationException e) {
            System.out.println("XML parse error: " + e.getMessage());
            return null;
        } catch (SAXException e) {
            System.out.println("Wrong XML file structure: " + e.getMessage());
                        return null;
        } catch (IOException e) {
            System.out.println("I/O exeption: " + e.getMessage());
            return null;
        }

            return doc;

    }


    /** Returns element value
      * @param elem element (it is XML tag)
      * @return Element value otherwise empty String
      */
     public final static String getElementValue( Node elem ) {
         Node kid;
         if( elem != null){
             if (elem.hasChildNodes()){
                 for( kid = elem.getFirstChild(); kid != null; kid = kid.getNextSibling() ){
                     if( kid.getNodeType() == Node.TEXT_NODE  ){
                         return kid.getNodeValue();
                     }
                 }
             }
         }
         return "";
     }

     /*Start Parsing Body */
     public static String getBodyXML(String id){     
            String line = null;
            try {
                DefaultHttpClient httpClient = new DefaultHttpClient();
                HttpPost httpPost = new HttpPost("http://192.168.1.44:9090/solr/core0/select/?q=content_id:"+id+"&version=2.2&start=0&rows=10&indent=on");
                HttpResponse httpResponse = httpClient.execute(httpPost);
                HttpEntity httpEntity = httpResponse.getEntity();
                line = EntityUtils.toString(httpEntity);

            } catch (UnsupportedEncodingException e) {
                line = "<results status=\"error\"><msg>Can't connect to server</msg></results>";
            } catch (MalformedURLException e) {
                line = "<results status=\"error\"><msg>Can't connect to server</msg></results>";
            } catch (IOException e) {
                line = "<results status=\"error\"><msg>Can't connect to server</msg></results>";
            }
            String st= ParseXMLBodyNode(line,"doc");
            return st;

    }

    public static String ParseXMLBodyNode(String str,String node){
         String xmlRecords = str;
         String results = "";
         String[] result = new String [1];
         StringBuffer sb = new StringBuffer();
         StringBuffer text = new StringBuffer(); 
         try {
             DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
             DocumentBuilder db = dbf.newDocumentBuilder();
             InputSource is = new InputSource();
             is.setCharacterStream(new StringReader(xmlRecords));
             Document doc = db.parse(is);
             NodeList indiatimes1 = doc.getElementsByTagName(node);
             sb.append("<results count=");
             sb.append("\"1\"");
             sb.append(">\r\n");

             for (int i = 0; i < indiatimes1.getLength(); i++) {
                Node node1 = indiatimes1.item(i);
                if (node1.getNodeType() == Node.ELEMENT_NODE) {
                    Element element = (Element) node1;
                    NodeList nodelist = element.getElementsByTagName("str");
                    Element element1 = (Element) nodelist.item(0);
                    NodeList title = element1.getChildNodes();
                    title.getLength();
                    for(int j=0; j<title.getLength();j++){
                        text.append(title.item(j).getNodeValue());
                    }
                    System.out.print((title.item(0)).getNodeValue());
                    sb.append("<result>\r\n");
                        sb.append("<body>");
                        String tmpText = html2text(text.toString());
                            sb.append("<![CDATA[<body>");
                            sb.append(tmpText);
                            sb.append("</body>]]>");
                        sb.append("</body>\r\n");
                    sb.append("</result>\r\n");
                    result[i] = title.item(0).getNodeValue();
                }
             }
             sb.append("</results>");
         } catch (Exception e) {
             System.out.println("Exception........"+results );
             e.printStackTrace();
         }
         return sb.toString();
     }
    /*End Parsing Body*/


    public static int numResults(Document doc){     
        Node results = doc.getDocumentElement();
        int res = -1;
        try{
            res = Integer.valueOf(results.getAttributes().getNamedItem("count").getNodeValue());
        }catch(Exception e ){
            res = -1;
        }
        return res;
    }

    public static String getValue(Element item, String str) {       
        NodeList n = item.getElementsByTagName(str);        
        return XMLfunctions.getElementValue(n.item(0));
    }


    public static String html2text(String html) {

        String pText = Jsoup.clean(html, Whitelist.basic());
        return pText;
    }

}

我称这些功能为

String xml = XMLfunctions.getBodyXML(id);

Document doc = XMLfunctions.XMLfromString(xml);

我希望字体标签作为xml中的html标签存在.

i want that the font tag be there as html tag in xml.

我们将不胜感激!!!!!!!

help would be appreciated!!!!!

推荐答案

将HTML包含在 CDATA部分,因此它不会被视为XML的一部分,而是普通文本:

Enclose your HTML in a CDATA section so it doesn't get treated as part of your XML, but instead just normal text:

<result>
<![CDATA[
    <body><font size="2px" face="arial">Hello World</font></body>
]]>
</result>

更新

您的问题可能在这里:

sb.append("<result>\r\n");
    sb.append("<body>");
    String tmpText = html2text(text.toString());
        sb.append("<![CDATA[<body>");
        sb.append(tmpText);
        sb.append("</body>]]>");
    sb.append("</body>\r\n");
sb.append("</result>\r\n");

注意 sb.append(< body>"); sb.append(</body> \ r \ n"); 行围绕您的CDATA部分,它们可能导致XML无法正确读取的问题.也许您应该删除这两行,使其看起来像这样:

Notice the sb.append("<body>"); and sb.append("</body>\r\n"); lines surrounding your CDATA section, they're probably causing the problem with your XML not being read correctly. Maybe you should remove those two lines so it looks like this:

sb.append("<result>\r\n");
    String tmpText = html2text(text.toString());
    sb.append("<![CDATA[<body>");
    sb.append(tmpText);
    sb.append("</body>]]>");
sb.append("</result>\r\n");

这篇关于将html标记存储在xml中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆