如何用R的xmlEventParse()获取XML特定属性
Absolutely! You absolutely can pull XML attributes just as simply as you’d hope in Python—no need for convoluted, hard-to-follow code. Let’s walk through a couple of straightforward methods, using a sample XML structure that matches your goal of grabbing a ViewCount attribute.
First, let’s assume your XML looks something like this (adjust based on your actual file’s structure):
<Post Id="123" ViewCount="1647" Title="Sample Question"> <Body>Some content here</Body> </Post>
Method 1: Use Python’s Built-in xml.etree.ElementTree
Python’s standard library has everything you need for basic XML parsing. The get() method makes grabbing attributes a breeze:
import xml.etree.ElementTree as ET # Parse your XML file tree = ET.parse('your_xml_file.xml') root = tree.getroot() # Grab the ViewCount attribute directly from the root element view_count = root.get('ViewCount') print(f"ViewCount : {view_count}") # If ViewCount is on a child element (e.g., a <Post> tag inside a root <Posts> element) # post_element = root.find('Post') # if post_element: # view_count = post_element.get('ViewCount') # print(f"ViewCount : {view_count}")
Method 2: Use xmltodict for Dictionary-like Access
If you prefer working with dictionaries (which feel more intuitive for many), the xmltodict library turns your XML into a Python dictionary. First install it with pip install xmltodict, then:
import xmltodict # Load and parse the XML file with open('your_xml_file.xml', 'r') as f: xml_dict = xmltodict.parse(f.read()) # Access the attribute using dictionary keys (adjust the path to match your XML structure) # For example, if your XML is wrapped in a <Root> tag: # view_count = xml_dict['Root']['Post']['@ViewCount'] view_count = xml_dict['Post']['@ViewCount'] print(f"ViewCount : {view_count}")
The @ prefix in xmltodict denotes XML attributes, so it’s easy to distinguish them from element content.
Just tweak the element paths to match your actual XML structure—once you target the right element, grabbing the attribute is as simple as a single line of code.
内容的提问来源于stack exchange,提问作者Lewis Wong

