2011-10-27 39 views
6

Tôi đang viết một ứng dụng bằng java bằng cách sử dụng nhập org.jdom. *;Cách lấy nội dung của nút từ JDOM

XML của tôi hợp lệ, nhưng đôi khi nó chứa thẻ HTML. Ví dụ: một cái gì đó như thế này:

<program-title>Anatomy &amp; Physiology</program-title> 
    <overview> 
     <content> 
       For more info click <a href="page.html">here</a> 
       <p>Learn more about the human body. Choose from a variety of Physiology (A&amp;P) designed for complementary therapies.&amp;#160; Online studies options are available.</p> 
     </content> 
    </overview> 
    <key-information> 
    <category>Health &amp; Human Services</category> 

Vì vậy, vấn đề của tôi là với các thẻ < p> bên trong nút overview.content.

Tôi đã hy vọng rằng mã này sẽ làm việc:

 Element overview = sds.getChild("overview"); 
     Element content = overview.getChild("content"); 

     System.out.println(content.getText()); 

nhưng nó sẽ trả về trống.

Làm cách nào để trả lại tất cả văn bản (thẻ lồng nhau và tất cả) từ nút overview.content?

Cảm ơn

+0

Hi, làm thế nào tôi có thể san bằng nút nội dung ra một cách đệ quy, khi văn bản được trộn lẫn với các nút khác. Ví dụ một siêu liên kết nằm ở giữa một câu. Tôi đã thêm tiền thưởng cho một số trợ giúp. –

+0

Cần lấy tất cả HTML bên trong thẻ nội dung, bao gồm một liên kết và danh sách có thứ tự. Cảm ơn –

Trả lời

0

Vấn đề là nút <content> không có con văn bản; nó có một con số <p> có chứa văn bản.

Hãy thử điều này:

Element overview = sds.getChild("overview"); 
Element content = overview.getChild("content"); 
Element p = content.getChild("p"); 
System.out.println(p.getText()); 

Nếu bạn muốn tất cả các nút con ngay lập tức, hãy gọi p.getChildren(). Nếu bạn muốn nhận được TẤT CẢ các nút con, bạn sẽ phải gọi nó một cách đệ quy.

+0

Và sau đó chỉ cần tự chuyển nút Loại phần tử thành biểu diễn văn bản ... Có lẽ đơn giản hơn những gì tôi đã nghĩ. –

4

Bạn có thể thử sử dụng method getValue() để biết gần đúng nhất, nhưng điều này làm cho nối tất cả văn bản trong phần tử và con cháu lại với nhau. Điều này sẽ không cung cấp cho bạn thẻ <p> dưới mọi hình thức. Nếu thẻ đó nằm trong XML của bạn như bạn đã hiển thị, nó đã trở thành một phần của đánh dấu XML. Nó cần phải được bao gồm dưới dạng &lt;p&gt; hoặc được nhúng trong phần CDATA để được coi là văn bản. Ngoài ra, nếu bạn biết tất cả các yếu tố có thể hoặc có thể không xuất hiện trong XML của bạn, bạn có thể áp dụng một phép biến đổi XSLT để biến những thứ không có ý định đánh dấu thành văn bản thuần túy.

+0

Câu trả lời hoàn hảo cho những người không cần tên phần tử trong nội dung hỗn hợp. Cảm ơn bạn! –

16

content.getText() cung cấp văn bản ngay lập tức chỉ hữu ích với các phần tử lá có nội dung văn bản.

Lừa là sử dụng org.jdom.output.XMLOutputter (với chế độ văn bản CompactFormat)

public static void main(String[] args) throws Exception { 
    SAXBuilder builder = new SAXBuilder(); 
    String xmlFileName = "a.xml"; 
    Document doc = builder.build(xmlFileName); 

    Element root = doc.getRootElement(); 
    Element overview = root.getChild("overview"); 
    Element content = overview.getChild("content"); 

    XMLOutputter outp = new XMLOutputter(); 

    outp.setFormat(Format.getCompactFormat()); 
    //outp.setFormat(Format.getRawFormat()); 
    //outp.setFormat(Format.getPrettyFormat()); 
    //outp.getFormat().setTextMode(Format.TextMode.PRESERVE); 

    StringWriter sw = new StringWriter(); 
    outp.output(content.getContent(), sw); 
    StringBuffer sb = sw.getBuffer(); 
    System.out.println(sb.toString()); 
} 

Output

For more info click<a href="page.html">here</a><p>Learn more about the human body. Choose from a variety of Physiology (A&amp;P) designed for complementary therapies.&amp;#160; Online studies options are available.</p> 

Do khám phá formatting lựa chọn khác và sửa đổi trên mã để nhu cầu của bạn.

"Class để đóng gói dạng tùy chọn XMLOutputter. Người sử dụng tiêu biểu có thể sử dụng các cấu hình tiêu chuẩn định dạng thu được bằng cách getRawFormat() (không có thay đổi khoảng trắng), getPrettyFormat() (khoảng trắng làm đẹp), và getCompactFormat() (khoảng trắng bình thường)."

+0

Cảm ơn người đàn ông !! –

3

Vâng, có lẽ đó là những gì bạn cần:

import java.io.StringReader; 

import org.custommonkey.xmlunit.XMLTestCase; 
import org.custommonkey.xmlunit.XMLUnit; 
import org.jdom.input.SAXBuilder; 
import org.jdom.output.XMLOutputter; 
import org.testng.annotations.Test; 
import org.xml.sax.InputSource; 

public class HowToGetNodeContentsJDOM extends XMLTestCase 
{ 
    private static final String XML = "<root>\n" + 
      " <program-title>Anatomy &amp; Physiology</program-title>\n" + 
      " <overview>\n" + 
      "  <content>\n" + 
      "    For more info click <a href=\"page.html\">here</a>\n" + 
      "    <p>Learn more about the human body. Choose from a variety of Physiology (A&amp;P) designed for complementary therapies.&amp;#160; Online studies options are available.</p>\n" + 
      "  </content>\n" + 
      " </overview>\n" + 
      " <key-information>\n" + 
      "  <category>Health &amp; Human Services</category>\n" + 
      " </key-information>\n" + 
      "</root>"; 
    private static final String EXPECTED = "For more info click <a href=\"page.html\">here</a>\n" + 
      "<p>Learn more about the human body. Choose from a variety of Physiology (A&amp;P) designed for complementary therapies.&amp;#160; Online studies options are available.</p>"; 

    @Test 
    public void test() throws Exception 
    { 
     XMLUnit.setIgnoreWhitespace(true); 
     Document document = new SAXBuilder().build(new InputSource(new StringReader(XML))); 
     List<Content> content = document.getRootElement().getChild("overview").getChild("content").getContent(); 
     String out = new XMLOutputter().outputString(content); 
     assertXMLEqual("<root>" + EXPECTED + "</root>", "<root>" + out + "</root>"); 
    } 
} 

Output:

PASSED: test on instance null(HowToGetNodeContentsJDOM) 

=============================================== 
    Default test 
    Tests run: 1, Failures: 0, Skips: 0 
=============================================== 

Tôi đang sử dụng JDOM với Generics: http://www.junlu.com/list/25/883674.html

Chỉnh sửa: Thực ra đó không phải là nhiều khác với câu trả lời của Prashant Bhate, có thể bạn cần nói cho chúng tôi biết bạn đang thiếu gì ...

0

Không đặc biệt là đẹp, nhưng hoạt động tốt (sử dụng JDOM API): giải pháp

public static String getRawText(Element element) { 
    if (element.getContent().size() == 0) { 
     return ""; 
    } 

    StringBuffer text = new StringBuffer(); 
    for (int i = 0; i < element.getContent().size(); i++) { 
     final Object obj = element.getContent().get(i); 
     if (obj instanceof Text) { 
      text.append(((Text) obj).getText()); 
     } else if (obj instanceof Element) { 
      Element e = (Element) obj; 
      text.append("<").append(e.getName()); 
      // dump all attributes 
      for (Attribute attribute : (List<Attribute>)e.getAttributes()) { 
       text.append(" ").append(attribute.getName()).append("=\"").append(attribute.getValue()).append("\""); 
      } 
      text.append(">"); 
      text.append(getRawText(e)).append("</").append(e.getName()).append(">"); 
     } 
    } 
    return text.toString(); 
} 

Prashant Bhate là đẹp hơn mặc dù!

1

Nếu bạn cũng tạo tệp XML, bạn sẽ có thể đóng gói dữ liệu html của mình theo số <![CDATA[]]> sao cho nó không được phân tích bởi trình phân tích cú pháp XML.

+0

Không, thật không may là tôi không tạo ra XML, tôi chỉ phải tiêu thụ nó. –

0

Nếu bạn muốn đầu ra các nội dung của một số nút JSOM chỉ cần sử dụng

System.out.println(new XMLOutputter().outputString(node)) 
Các vấn đề liên quan