How do I parse the content in Comments of Mechanical DataModelTree?

Ayush Kumar
Ayush Kumar Member, Moderator, Employee Posts: 472
100 Answers 250 Likes 100 Comments Second Anniversary
✭✭✭✭
edited June 2023 in Structures

I have to parse the contents in Mechanical DataModelTree Comment to retrieve and send the data in further down the chain in a customized workflow.

enter image description here

enter image description here

Tagged:

Answers

  • Ayush Kumar
    Ayush Kumar Member, Moderator, Employee Posts: 472
    100 Answers 250 Likes 100 Comments Second Anniversary
    ✭✭✭✭
    Answer ✓

    The comment object - Ansys.ACT.Automation.Mechanical.Comment uses HTML syntax to render data. So you can use standard IronPython library HTMLParser in the Mechanical Scripting Console.

    from HTMLParser import HTMLParser
    
    class MyHTMLParser(HTMLParser):
    
        def handle_starttag(self, tag, attrs):
            u"""
             Executed each time start tag is found.
             """
            print "Encountered the beginning of a %s tag" % tag
    
        def handle_data(self, data):
            u"""
             Executed each time data is encountered.
             """
            print "Encountered data - %s" % data
    
        def handle_endtag(self, tag):
            u"""
             Executed each time an endtag is found.
             """
            print "Encountered the end of a %s tag" % tag
    
    

    The above mentioned class inherits from HTMLParser, you can define other functions in the class to extend the functionality of the parent class.

    Example usage:

    # Select a comment in the DataModelTree
    comment = Tree.FirstActiveObject
    
    html_parser = MyHTMLParser()
    html_parser.feed(comment.Text)
    

    Output:

    Encountered the beginning of a p tag
    Encountered data - This is sample text 1.
    Encountered the beginning of a br tag
    Encountered data - This is sample text 2.
    Encountered the beginning of a br tag
    Encountered data - This is sample text 3.
    Encountered the end of a p tag