簡體   English   中英

使用Python解析XML

[英]parse XML using Python

<?xml version="1.0" encoding="UTF-8"?>
<WindowElement xmlns="http://windows.lbl.gov">
    <WindowElementType>System</WindowElementType>
    <Optical>
        <WavelengthData>
            <LayerNumber>System</LayerNumber>
            <Wavelength unit="Integral">Visible</Wavelength>
            <SourceSpectrum>CIE Illuminant D65 1nm.ssp</SourceSpectrum>
            <DetectorSpectrum>ASTM E308 1931 Y.dsp</DetectorSpectrum>
            <WavelengthDataBlock>
                <WavelengthDataDirection>Transmission Front</WavelengthDataDirection>
                <ColumnAngleBasis>LBNL/Klems Full</ColumnAngleBasis>
                <RowAngleBasis>LBNL/Klems Full</RowAngleBasis>
                <ScatteringDataType>BTDF</ScatteringDataType>
                <ScatteringData> 1, 2, 3, 3 
                             </ScatteringData>
            </WavelengthDataBlock>
        </WavelengthData>
    <WavelengthData>
        <LayerNumber>System</LayerNumber>
        <Wavelength unit="Integral">Visible</Wavelength>
        <SourceSpectrum>CIE Illuminant D65 1nm.ssp</SourceSpectrum>
        <DetectorSpectrum>ASTM E308 1931 Y.dsp</DetectorSpectrum>
        <WavelengthDataBlock>
            <WavelengthDataDirection>Transmission Back</WavelengthDataDirection>
            <ColumnAngleBasis>LBNL/Klems Full</ColumnAngleBasis>
            <RowAngleBasis>LBNL/Klems Full</RowAngleBasis>
            <ScatteringDataType>BTDF</ScatteringDataType>
            <ScatteringData> 555, 555
.......

如何使用Python來讀1, 2, 3, 3在ScatteringData元素,並將其改變為5, 8, 8

有兩個稱為ScatteringData的元素,只有第一個被更改。

謝謝!

您應該查看可用於在python中使用XML的庫。 您可以從這里開始http://wiki.python.org/moin/PythonXml

如果您必須處理xml,建議您看一下lxml

他們說lxml是功能最豐富,最易用的庫,用於處理Python語言中的XML和HTML。 而且它比其他選擇更快,更強大。 並在SO中搜索lxml等,因為在先前的問題中有很多關於使用哪個的建議。

from lxml import etree as ET

In [14]: root = ET.fromstring(datafragment)

In [15]: root.xpath('.//scatteringdata')[0].text='blah'

In [16]: print ET.tostring(root,pretty_print=True)
...
<scatteringdata>blah</scatteringdata>
...

如果必須在一個以上的地方進行更改,請使用循環:

for i in root.xpath('.//scatteringdata'):
    i.text='smth'

這是使用美麗湯的解決方案。 基本上,它使您可以瀏覽數據並根據需要進行修改。

import BeautifulSoup
soup = BeautifulSoup.BeautifulSoup(open("waves.xml"))
soup.scatteringdata.string = "5, 8, 8"
print soup.prettify()

哪個輸出:

  ...
  <scatteringdatatype>
    BTDF
   </scatteringdatatype>
   <scatteringdata>
    5, 8, 8
   </scatteringdata>
  </wavelengthdatablock>
  ...

如果您想先看一下數據,可以使用

originalData = soup.scatteringdata.string 

然后按需處理

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM