【问题标题】:HTML structure varying on inputHTML 结构因输入而异
【发布时间】:2014-11-07 11:44:48
【问题描述】:

我有一个包含动态 HTML 的字符串。 HTML 可以包含静态图像、地图、文本、链接等。您可以查看this link

当我有文本和链接 (a href) 时,这个问题的答案是有效的。但是,如果 html 包含图像或地图,则它会出现故障并且 html 不会按预期生成。

我为完成这项工作而创建的方法是:

private void createHtmlWeb(){

        String listOfElements = "null"; // normally found if
                                        // webTextcontains.maps.google.com
        Toast.makeText(getApplicationContext(), "" + mainEditText.getHeight(), Toast.LENGTH_SHORT).show();
        ParseObject postObject = new ParseObject("Post");
        Spannable s = mainEditText.getText();
        String webText = Html.toHtml(s);
        webText = webText.replaceAll("(</?(?:b|i|u)>)\\1+", "$1").replaceAll("</(b|i|u)><\\1>", "");

        // Logic to add center tag before image
//      Document doc = Jsoup.parse(webText);
//      Elements imgs = doc.select("img");
//      for (Element img : imgs) {
//          img.attr("src", "images/" + img.attr("src")); // or whatever
//      }
//
//      doc.outerHtml(); // returns the modified HTML
        //Determine link and favourite types to add favourite a class around it.

        // Determine link and favourite types to add favourite a class around
        // it.
        if (webText.contains("a href")) {
            String favourite = "favourite";
            // Parse it into jsoup
            Document doc = Jsoup.parse(webText);
            // Create an array to tackle every type individually as wrap can
            // affect whole body types otherwises.
            Element[] array = new Element[doc.select("a").size()];

            for (int i = 0; i < doc.select("a").size(); i++) {
                if (doc.select("a").get(i) != null) {
                    array[i] = doc.select("a").get(i);
                }
            }

            for (int i = 0; i < array.length; i++) {
                // we don't want to wrap link types. Common part links have is
                // http. Should update for somethng more secure.
                if (array[i].toString().contains("http") == false) {
                    // wrapping inner href with a tag attributes
                    Elements link = doc.select("a");
                    String linkHref = link.attr("href");
                    Log.e("linkHref",linkHref);
                    array[i] = array[i].wrap("<a class=" + favourite + " href='"+linkHref+"'></a>");
                }

            }
            // Log.e("From doc.body html *************** ", " " + doc.body());
            Element element = doc.body();
            Log.e("From element html *************** ", " " + element.html());
            //changes to update html ahref
            String currentHtml = element.html();
            String newHtml = currentHtml.substring(0,currentHtml.indexOf("<a href")+1)+currentHtml.substring(currentHtml.indexOf("font"),currentHtml.indexOf("</a>"))+currentHtml.substring(currentHtml.indexOf("</a>")+4,currentHtml.length());
            listOfElements = newHtml;
            //refactoring html
            listOfElements = wrapImgWithCenter(listOfElements);
            //listOfElements = element.html();
        }

        // First need to do a check of the code if iti s a google maps image
        if (webText.contains("maps.google.com")) {
            Document doc = Jsoup.parse(webText); // Parse it into jsoup

            for (int i = 0; i < doc.select("img").size(); i++) {
                if (doc.select("img").get(i).toString().contains("maps.google.com")) {
                    // Get all numbers + full stops + get all numbers
                    Pattern noImage = Pattern.compile("(\\-?\\d+(\\.\\d+)?),(\\-?\\d+(\\.\\d+))+%7C(\\-?\\d+(\\.\\d+)?),(\\-?\\d+(\\.\\d+))");
                    // Gets the URL SRC basically.. almost.. lets try it
                    Matcher matcherer = noImage.matcher(doc.select("img").get(i).toString());

                    // Have two options - multi route or single route
                    if (matcherer.find() == true) {
                        for (int j = 0; j < matcherer.groupCount(); j++) {
                            latitude_to = Double.parseDouble(matcherer.group(1));
                            longitude_to = Double.parseDouble(matcherer.group(3));
                            latitude_from = Double.parseDouble(matcherer.group(5));
                            longitude_from = Double.parseDouble(matcherer.group(7));
                        }

                        String coOrds = "" + latitude_to + "," + longitude_to + "," + latitude_from + "," + longitude_from;
                        Element ele = doc.body();
                        ele.select("img").get(i).wrap("<a href=" + coOrds + "></a>");
                        listOfElements = ele.html();
                        listOfElements = listOfElements.replace("&amp;", "&");

                    } else if (matcherer.find() == false) {
                        noImage = Pattern.compile("(\\-?\\d+(\\.\\d+)?),\\s*(\\-?\\d+(\\.\\d+)?)");
                        matcherer = noImage.matcher(doc.select("img").get(i).toString());

                        Toast.makeText(getApplicationContext(), "Regex Count:" + matcherer.groupCount(), Toast.LENGTH_LONG).show();
                        if (matcherer.find()) {
                            for (int j = 0; j < matcherer.groupCount(); j++) {
                                latitude = Double.parseDouble(matcherer.group(1));
                                parseGeoPoint.setLatitude(latitude);
                                longitude = Double.parseDouble(matcherer.group(3));
                                parseGeoPoint.setLongitude(longitude);
                            }
                        }

                        String coOrds = "" + latitude + "," + longitude;

                        Element ele = doc.body();
                        ele.select("img").get(i).wrap("<a href=" + coOrds + "></a>");
                        listOfElements = ele.html();
                        listOfElements = listOfElements.replace("&amp;", "&");

                    }

                } else {
                    // standard photo
                    Element ele = doc.body();
                    ele.select("img").get(i);
                    listOfElements = ele.html();

                }

            }
            Log.e("listOfElements", listOfElements);
            //refactoring html
            listOfElements = wrapImgWithCenter(listOfElements);
            // Put new value in htmlContent
            postObject.put("htmlContent", listOfElements);

        } else {
            //refactoring html
            webText = wrapImgWithCenter(webText);
            postObject.put("htmlContent", webText);
        }

        mainEditText.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {

            @Override
            public void onGlobalLayout(){
                // TODO Auto-generated method stub
                Rect r = new Rect();
                mainEditText.getWindowVisibleDisplayFrame(r);

                // int screenHeight = mainEditText.getRootView().getHeight();
                // int heightDifference = screenHeight - (r.bottom - r.top);
            }
        });

        // See if a trip exists
        if (finalTrip != null) {
        }

        // Want to put the location in the location section
        // if parsegeoPoint != null -- old information
        if (latitude != -10000 && longitude != -10000) {
            // Toast.makeText(getApplicationContext(),
            // "Adding in location co-ods: " + latitude + " : " + longitude ,
            // Toast.LENGTH_SHORT).show();
            postObject.put("location", parseGeoPoint);
        }
        postObject.put("type", Post.PostType.HTML.getPostVal());
        postObject.put("user", ParseObject.createWithoutData("_User", user.getObjectId()));

        // Transfer these details
        Intent i = new Intent(getApplicationContext(), WriteStoryAnimation.class);
        i.putExtra("listOfElements", listOfElements);
        i.putExtra("webText", webText);
        i.putExtra("finalTrip", finalTrip);
        i.putExtra("latitude", latitude);
        i.putExtra("longitude", longitude);

        if(mainEditText.length() > 0){
            finish();
            //Conflict was here from html merge.
            startActivity(i);
        } else {
            Toast.makeText(getApplicationContext(), "Your story is empty", Toast.LENGTH_SHORT).show();
        }

        // finish();
        // Toast.makeText(getApplicationContext(), "EditText Sie: " + height +
        // " : " + desiredHeight, Toast.LENGTH_LONG).show();

    }

    // method to refactor html
    public String wrapImgWithCenter(String html){
         Document doc = Jsoup.parse(html);
         //adding center tag before images
            doc.select("img").wrap("<center></center>");
            //adding gap after last p tag
            for (int i =0; i<= 1; i++) {
            doc.select("p").last().after("<br>");
            }
          Log.e("Wrapping", doc.html());
            return doc.html();
    } 

您必须阅读链接中的问题才能理解输入和输出。

其他带有图片和链接的输出供您参考:

<html>
 <head></head>
 <body>
  <p dir="ltr">
   <center>
    <img src="http://files.parsetfss.com/bcff7108-cbce-4ab8-b5d1-1f82827e6519/tfss-9fca384a-2f7b-4632-a585-65c78f40842a-file" />
   </center><br /> <a href="LixWQfueLU"><font color="#009a49">Rohit Lalwani</font></a><br /> <a href="45.5033204,-99.8865083">
    <center>
     <img src="http://maps.google.com/maps/api/staticmap?center=45.5033204,-99.8865083&amp;zoom=15&amp;size=960x540&amp;sensor=false&amp;markers=color:blue%7Clabel:!%7C45.5033204,-99.8865083" />
    </center></a><br /> </p>
  <br />
  <br />
 </body>
</html>

您可以看到href 标记中的class="favourite" 缺失。这是我需要纠正的。请建议我该怎么做。

【问题讨论】:

  • 天哪!我回答了最初的问题,我会复制/粘贴这个问题的答案。

标签: java android regex jsoup


【解决方案1】:

阅读您的原始问题,我发现您可以通过这种方式实现您想要的:

  1. 你有一个主播 (a.favorite)
  2. 你必须选择他的孙子(font 在这种特殊情况下,但它可以是img 或其他)
  3. 你删除了原锚点的孩子
  4. 然后您将孙辈追加为新的孩子!。

这听起来可能很复杂,但其实很简单,这里有一个代码示例:

    String html ="<a class=\"favourite\" href=\"LixWQfueLU\"><a href=\"LixWQfueLU\"><font color=\"#009a49\">Rohit Lalwani</font></a></a>";
    Document doc = Jsoup.parse(html);
    //The original anchor
    Element afav = doc.select(".favourite").first();
    //The grandchild
    Element select = doc.select("font").first();
    afav.remove();
    afav.appendChild(select);
    System.out.println(afav);

输出:

<a class="favourite" href="LixWQfueLU"><font color="#009a49">Rohit Lalwani</font></a>

希望对你有帮助!

猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-12-13
  • 1970-01-01
  • 2020-12-11
  • 1970-01-01
  • 1970-01-01
  • 2016-12-19
  • 1970-01-01
相关资源
最近更新 更多