2014-11-07 4 views
1

동적 HTML이 포함 된 문자열이 있습니다. HTML에는 정적 이미지,지도, 텍스트, 링크 등이 포함될 수 있습니다. this link을 살펴볼 수 있습니다.HTML 구조가 입력시 달라짐

텍스트 및 링크 (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"이없는 것을 볼 수 있습니다. 이것이 내가 교정 할 필요가있는 것입니다. 어떻게해야할지 제안 해주세요.

+0

오, 이런! 나는 원래 질문에 대답했다, 나는 이것을 복사/붙여 넣을 것이다. – fonkap

답변

2

나는 당신이이 방법으로 원하는 것을 달성 할 수있는 것으로 확인 원래의 질문에 읽기 : 당신은 앵커가

  1. 을 (a.favorite)
  2. 당신은이 특별한 경우에 자신의 손자 ( font을 선택해야
  3. 하지만, img 또는 무엇이든간에)
  4. 원래 앵커의 자식을 삭제하면
  5. 입니다. 그런 다음 손자를 새로운 자식으로 추가 할 수 있습니다.

이 복잡하게 들릴 수는 있지만 매우 간단합니다, 여기 당신은 코드 예제입니다 :

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> 

는 희망이 도움이!

+0

http://stackoverflow.com/questions/26840538/re-factor-html-structure를 참조하십시오. – kittu88

관련 문제