XML 文件解析 Python
XML file parsing Python
我在收集另外 2 条数据以使用 Python
从 XML 转换为 CSV 时遇到问题
它们是描述标签和生成标签。
对于描述标签,我尝试了 item.find('description').text
但没有成功。
对于 generatedOn 标签,我希望它像这样连接其中的项目:
请参阅下面的示例 XML:
<?xml version="1.0" encoding="UTF-8"?>
<omGroups xmlns="urn:nortel:namespaces:mcp:oms" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="urn:nortel:namespaces:mcp:oms OMSchema.xsd" >
<group>
<name>RecordingSystem</name>
<row>
<package>com.nortelnetworks.mcp.ne.base.recsystem.fw.system</package>
<class>RecSysFileOMRow</class>
<usage name="closedFileCount" hasThresholds="true">
<measures>
closed file count
</measures>
<description>
This register counts the number
of closed files in the spool directory of a
particular stream and a particular system.
Files in the spool directory store the raw
OAM records where they are sent to the
Element Manager for formatting.
</description>
<notes>
Minor and major alarms
when the value of closedFileCount
exceeds certain thresholds. Configure
the threshold values for minor and major
alarms for this OM through engineering
parameters for minorBackLogCount and
majorBackLogCount, respectively. These
engineering parameters are grouped under
the parameter group of Log, OM, and
Accounting for the logs’ corresponding
system.
</notes>
</usage>
<usage name="processedFileCount" hasThresholds="true">
<measures>
Processed file count
</measures>
<description>
The register counts the number
of processed files in the spool directory of
a particular stream and a particular system.
Files in the spool directory store the raw
OAM records and then send the records to
the Element Manager for formatting.
</description>
</usage>
</row>
<documentation>
<description>
Rows of this OM group provide a count of the number of files contained
within the directory (which is the OM row key value).
</description>
<rowKey>
The full name of the directory containing the files counted by this row.
</rowKey>
</documentation>
<generatedOn>
<all/>
</generatedOn>
</group>
<group traffic="true">
<name>Ports</name>
<row>
<package>com.nortelnetworks.ims.cap.mediaportal.host</package>
<class>PortsOMRow</class>
<usage name="rtpMpPortUsage">
<measures>
BCP port usage
</measures>
<description>
Meter showing number of ports in use.
</description>
</usage>
<lwGauge name="connMapEntriesLWM">
<measures>
Lowest simultaneous port usage
</measures>
<description>
Lowest number of
simultaneous ports detected to be in
use during the collection interval
</description>
</lwGauge>
<hwGauge name="connMapEntriesHWM">
<measures>
Highest simultaneous port usage
</measures>
<description>
Highest number of
simultaneous ports detected to be in
use during the collection interval.
</description>
</hwGauge>
<waterMark name="connMapEntries">
<measures>
Connections map entries
</measures>
<description>
Meter showing the number of connections in the host
CPU connection map.
</description>
<bwg lwref="connMapEntriesLWM" hwref="connMapEntriesHWM"/>
</waterMark>
<counter name="portUsageSampleCnt">
<measures>
Usage sample count
</measures>
<description>
The number of 100-second samples taken during the
collection interval contributing to the average report.
</description>
</counter>
<counter name="sampledRtpMpPortUsage">
<measures>
In-use ports usage
</measures>
<description>
Provides the sum of the in-use ports every 100 seconds.
</description>
</counter>
<precollector>
<package>com.nortelnetworks.ims.cap.mediaportal.host</package>
<class>PortsOMCenturyPrecollector</class>
<collector>centurySecond</collector>
</precollector>
</row>
<documentation>
<description>
</description>
<rowKey>
</rowKey>
</documentation>
<generatedOn>
<list>
<ne>sessmgr</ne>
<ne>rtpportal</ne>
</list>
</generatedOn>
</group>
</omGroups>
代码
import csv
from bs4 import BeautifulSoup
soup = BeautifulSoup(xml_string, 'html.parser')
with open('data.csv', 'w', newline='') as f_out:
writer = csv.writer(f_out)
writer.writerow(['General name:SpecificName', 'RegisterType', 'Measures'])
for item in soup.select('row [name]'):
writer.writerow([item.find_previous('name').text + ':' + item['name'], item.name, item.find('measures').get_text(strip=True)])
你可以试试这个代码:
import csv
import re
from bs4 import BeautifulSoup
soup = BeautifulSoup(xml_string, 'html.parser')
with open('data.csv', 'w', newline='') as f_out:
writer = csv.writer(f_out)
writer.writerow(['General name:SpecificName', 'RegisterType', 'Measures', 'Description', 'generatedOn'])
for item in soup.select('row [name]'):
desc = item.find('description').get_text(strip=True)
desc = re.sub(r'\s{2,}', ' ', desc)
generatedOn = ','.join(ne.get_text(strip=True) for ne in item.find_parent('group').select('ne'))
writer.writerow([item.find_previous('name').text + ':' + item['name'], item.name, item.find('measures').get_text(strip=True), desc, generatedOn])
生成 data.csv
:
我在收集另外 2 条数据以使用 Python
从 XML 转换为 CSV 时遇到问题它们是描述标签和生成标签。
对于描述标签,我尝试了 item.find('description').text
但没有成功。
对于 generatedOn 标签,我希望它像这样连接其中的项目:
请参阅下面的示例 XML:
<?xml version="1.0" encoding="UTF-8"?>
<omGroups xmlns="urn:nortel:namespaces:mcp:oms" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="urn:nortel:namespaces:mcp:oms OMSchema.xsd" >
<group>
<name>RecordingSystem</name>
<row>
<package>com.nortelnetworks.mcp.ne.base.recsystem.fw.system</package>
<class>RecSysFileOMRow</class>
<usage name="closedFileCount" hasThresholds="true">
<measures>
closed file count
</measures>
<description>
This register counts the number
of closed files in the spool directory of a
particular stream and a particular system.
Files in the spool directory store the raw
OAM records where they are sent to the
Element Manager for formatting.
</description>
<notes>
Minor and major alarms
when the value of closedFileCount
exceeds certain thresholds. Configure
the threshold values for minor and major
alarms for this OM through engineering
parameters for minorBackLogCount and
majorBackLogCount, respectively. These
engineering parameters are grouped under
the parameter group of Log, OM, and
Accounting for the logs’ corresponding
system.
</notes>
</usage>
<usage name="processedFileCount" hasThresholds="true">
<measures>
Processed file count
</measures>
<description>
The register counts the number
of processed files in the spool directory of
a particular stream and a particular system.
Files in the spool directory store the raw
OAM records and then send the records to
the Element Manager for formatting.
</description>
</usage>
</row>
<documentation>
<description>
Rows of this OM group provide a count of the number of files contained
within the directory (which is the OM row key value).
</description>
<rowKey>
The full name of the directory containing the files counted by this row.
</rowKey>
</documentation>
<generatedOn>
<all/>
</generatedOn>
</group>
<group traffic="true">
<name>Ports</name>
<row>
<package>com.nortelnetworks.ims.cap.mediaportal.host</package>
<class>PortsOMRow</class>
<usage name="rtpMpPortUsage">
<measures>
BCP port usage
</measures>
<description>
Meter showing number of ports in use.
</description>
</usage>
<lwGauge name="connMapEntriesLWM">
<measures>
Lowest simultaneous port usage
</measures>
<description>
Lowest number of
simultaneous ports detected to be in
use during the collection interval
</description>
</lwGauge>
<hwGauge name="connMapEntriesHWM">
<measures>
Highest simultaneous port usage
</measures>
<description>
Highest number of
simultaneous ports detected to be in
use during the collection interval.
</description>
</hwGauge>
<waterMark name="connMapEntries">
<measures>
Connections map entries
</measures>
<description>
Meter showing the number of connections in the host
CPU connection map.
</description>
<bwg lwref="connMapEntriesLWM" hwref="connMapEntriesHWM"/>
</waterMark>
<counter name="portUsageSampleCnt">
<measures>
Usage sample count
</measures>
<description>
The number of 100-second samples taken during the
collection interval contributing to the average report.
</description>
</counter>
<counter name="sampledRtpMpPortUsage">
<measures>
In-use ports usage
</measures>
<description>
Provides the sum of the in-use ports every 100 seconds.
</description>
</counter>
<precollector>
<package>com.nortelnetworks.ims.cap.mediaportal.host</package>
<class>PortsOMCenturyPrecollector</class>
<collector>centurySecond</collector>
</precollector>
</row>
<documentation>
<description>
</description>
<rowKey>
</rowKey>
</documentation>
<generatedOn>
<list>
<ne>sessmgr</ne>
<ne>rtpportal</ne>
</list>
</generatedOn>
</group>
</omGroups>
代码
import csv
from bs4 import BeautifulSoup
soup = BeautifulSoup(xml_string, 'html.parser')
with open('data.csv', 'w', newline='') as f_out:
writer = csv.writer(f_out)
writer.writerow(['General name:SpecificName', 'RegisterType', 'Measures'])
for item in soup.select('row [name]'):
writer.writerow([item.find_previous('name').text + ':' + item['name'], item.name, item.find('measures').get_text(strip=True)])
你可以试试这个代码:
import csv
import re
from bs4 import BeautifulSoup
soup = BeautifulSoup(xml_string, 'html.parser')
with open('data.csv', 'w', newline='') as f_out:
writer = csv.writer(f_out)
writer.writerow(['General name:SpecificName', 'RegisterType', 'Measures', 'Description', 'generatedOn'])
for item in soup.select('row [name]'):
desc = item.find('description').get_text(strip=True)
desc = re.sub(r'\s{2,}', ' ', desc)
generatedOn = ','.join(ne.get_text(strip=True) for ne in item.find_parent('group').select('ne'))
writer.writerow([item.find_previous('name').text + ':' + item['name'], item.name, item.find('measures').get_text(strip=True), desc, generatedOn])
生成 data.csv
: