使用Python提取指定XML中Identity产品的IPv4地址列表
Absolutely! You can target the exact elements you need without manually traversing the entire root node—XPath queries are your best friend here for efficient XML parsing. Since converting this XML to JSON is causing headaches, let’s skip that entirely and go straight to extracting the Identity product’s IPv4 addresses with Python’s built-in tools.
Here’s a clean, straightforward solution using Python’s standard xml.etree.ElementTree module (no extra dependencies needed):
import xml.etree.ElementTree as ET from urllib.request import urlopen # Fetch and parse the Office 365 IP address XML xml_url = "https://support.content.office.net/en-us/static/O365IPAddresses.xml" with urlopen(xml_url) as response: xml_tree = ET.parse(response) # Use an XPath query to directly select IPv4 addresses under the "Identity" product identity_ipv4_list = [ ip_element.text.strip() for ip_element in xml_tree.findall(".//Product[Name='Identity']/Ipv4Addresses/Ipv4") ] # Now you have all the IPv4 addresses stored in a Python list print(identity_ipv4_list)
How this works:
- The XPath expression
.//Product[Name='Identity']/Ipv4Addresses/Ipv4directly navigates to:- Any
<Product>node where the child<Name>equals "Identity" - Then drills down to its
<Ipv4Addresses>container - Finally selects all child
<Ipv4>nodes
- Any
- We loop through these nodes, strip any extra whitespace from their text content, and collect them into a Python list.
Why this is better than converting to JSON:
XML structures like this often have repeating nested nodes and flexible schemas, which can get mangled during JSON conversion (leading to unexpected nested lists or key conflicts). Using XPath lets you work directly with the XML’s native structure to target exactly what you need, no conversion headaches required.
If you need more robust XPath support (like handling namespaces, though this XML doesn’t use them), you could use the lxml library instead—but the standard library solution works perfectly for this scenario.
内容的提问来源于stack exchange,提问作者Dan Walker

