Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
330 views
in Technique[技术] by (71.8m points)

c# - HTML to List using XMLWorker

Could somebody please provide an example of parsing HTML into a list of elements using XMLWorkerHelper in iTextSharp (C#).

The JAVA version as given in the documentation is:

XMLWorkerHelper.getInstance().parseXHtml(new ElementHandler() {
        public void add(final Writable w) {

          if (w instanceof WritableElement) {
            List<Element> elements = ((WritableElement)w).elements();
          // write class names of elements to file
         }
        }

     }, HTMLParsingToList.class.getResourceAsStream("/html/walden.html"));
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You need to implement the IElementHandler interface in a class of your own:

public class SampleHandler : IElementHandler {
    //Generic list of elements
    public List<IElement> elements = new List<IElement>();
    //Add the supplied item to the list
    public void Add(IWritable w) {
        if (w is WritableElement) {
            elements.AddRange(((WritableElement)w).Elements());
        }
    }
}

Instead of using the file stream here's an example parsing a string. To use a file replace the StringReader with a StreamReader.

    string html = "<html><head><title>Test Document</title></head><body><p>This is a test. <strong>Bold <em>and italic</em></strong></p><ol><li>Dog</li><li>Cat</li></ol></body></html>";
    //Instantiate our handler
    var mh = new SampleHandler();
    //Bind a reader to our text
    using (TextReader sr = new StringReader(html)) {
        //Parse
        XMLWorkerHelper.GetInstance().ParseXHtml(mh, sr);
    }

    //Loop through each element
    foreach (var element in mh.elements) {
        //Loop through each chunk in each element
        foreach (var chunk in element.Chunks) {
            //Do something
        }
    }

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...