0

--XSLTについて少し学んだ後でも、metadata / xls形式が変更されたため、XSLTを使用しなかったため、単一のスタイルシートベースのアプローチは機能しません---

過去数時間、csvを取得して各タグのデータをCSVにダンプしようとしましたが、何も機能しませんでした。フォーラムの他のいくつかのQ&Aに基づいて、elemtree、parse、およびregexを試しました。

たとえば彼のテストデータでは正常に機能しますが、私のxmlでは機能しません(質問の最後のサンプル)。

tree = ET.parse("test2.xml")
doc = tree.getroot()
thingy = doc.find('custod')
print thingy.attrib

トレースバック(最後の最後の呼び出し):ファイル ""、1行目、AttributeError:'NoneType'オブジェクトには属性'attrib'がありません

doc
<Element anzmeta at 801a300>
thingy = doc.find('anzmeta')
print thingy.attrib

トレースバック(最後の最後の呼び出し):ファイル ""、1行目、AttributeError:'NoneType'オブジェクトには属性'attrib'がありません

doc.attrib
{}

--- REXを使用してみてください

rex = re.compile(r'<custod.*?>(.*?)</custod>',re.S|re.M)
rex
<_sre.SRE_Pattern object at 0x080724A0>
match=rex.match('test2.xml')
match
text = match.groups()[0].strip()

トレースバック(最後の最後の呼び出し):ファイル ""、1行目、AttributeError:'NoneType'オブジェクトには属性'groups'がありません


必要なのは、システムがxmlファイルを調べて、csvの列に各タグの完全なエントリを持つcsvを作成することだけです。列が存在しない場合はcsvに列を追加し、それに応じて列を設定する必要があります。

===========XMLサンプル

<?xml version="1.0" encoding="utf-8"?>
<?xml-stylesheet type='text/xsl' href='ANZMeta.xsl'?>
<anzmeta>
  <citeinfo>
    <uniqueid />
    <title>&lt;&gt;</title>
    <origin>
      <custod>ATGIS</custod>
      <jurisdic>
        <keyword thesaurus="">Tablelands Regional Council</keyword>
      </jurisdic>
    </origin>
  </citeinfo>
  <descript>
    <abstract>&lt;&gt;
    </abstract>
    <theme>
      <keyword thesaurus="">EPSG</keyword>
    </theme>
    <spdom>
      <keyword thesaurus="">GDA94</keyword>
      <keyword thesaurus="">GRS80</keyword>
      <keyword thesaurus="">Map Grid of Australia</keyword>
      <keyword thesaurus="">Zone 55 (144E - 150E)</keyword>
      <bounding>
        <northbc />
        <southbc />
        <eastbc />
        <westbc />
      </bounding>
    </spdom>
  </descript>
  <timeperd>
    <begdate>
      <date>2012</date>
    </begdate>
    <enddate>
      <keyword thesaurus="">Completed</keyword>
    </enddate>
  </timeperd>
  <status>
    <progress>
      <keyword thesaurus="">Ongoing</keyword>
      <keyword thesaurus="">Completed</keyword>
    </progress>
    <update>
      <keyword thesaurus="">As Required</keyword>
      <keyword thesaurus="">As Required</keyword>
    </update>
  </status>
  <distinfo>
    <native>
      <nondig>
        <formname>File</formname>
      </nondig>
      <digform>
        <formname>Type:</formname>
      </digform>
    </native>
    <avlform>
      <nondig>
        <formname>Format:</formname>
      </nondig>
      <digform>
        <formname>Size</formname>
      </digform>
    </avlform>
    <accconst>Internal Use Only</accconst>
  </distinfo>
  <dataqual>
    <lineage>~TBC~</lineage>
    <procstep>
      <procdesc Sync="TUE">Metadata imported.</procdesc>
      <srcused Sync="TRUE">L:\Data_Admin\MetadataGenerator\trc_Metadata_Template.xml</srcused>
      <date Sync="TRUE">20121206</date>
      <time Sync="TRUE">15341400</time>
    </procstep>
    <posacc>~TBC~</posacc>
    <attracc>~TBC~</attracc>
    <logic>~TBC~</logic>
    <complete>~TBC~</complete>
  </dataqual>
  <cntinfo>
    <cntorg>Atherton Tablelands GIS</cntorg>
    <cntpos>GIS Coordinator</cntpos>
    <address>PO Box 1616, 8 Tolga Rd</address>
    <city>Atherton</city>
    <state>QLD</state>
    <country>AUSTRALIA</country>
    <postal>4883</postal>
    <cntvoice>07 40918600</cntvoice>
    <cntfax>07 40917035</cntfax>
    <cntemail>info@atgis.com.au</cntemail>
  </cntinfo>
  <metainfo>
    <metd>
      <date />
    </metd>
  </metainfo>
</anzmeta>

---スクリプトの開始

import os, xml, shutil, datetime
from xml.etree import ElementTree as et

SourceDIR=os.getcwd()
outDIR=os.getcwd()+'//out'

def locatexml(SourceDIR,outDIR):
    xmllist=[]
    for root, dirs, files in os.walk(SourceDIR, topdown=False):
        for fl in files:
            currentFile=os.path.join(root, fl)
            ext=fl[fl.rfind('.')+1:]
            if ext=='xml':
                xmllist.append(currentFile)
                print currentFile
                readxml(currentFile)
    print "finished"
    return xmllist

def readxml(currentFile):
    tree=et.parse(currentFile)
    print "Processing: "+str(currentFile)

locatexml(SourceDIR,outDIR)
print xmllist
4

2 に答える 2

1

XMLを別の形式に変換するため、このジョブを実行するにはXSLTを実際に使用する必要があります。例については、この質問の回答を参照してください。

ただし、他の理由でそれを実行したい場合lxmlは、次のコードを使用して開始できます。

from lxml import etree

with open('test.xml') as f:
    tree = etree.parse(f)

# At this point, we can step through the xml file
# and parse it, here is an example of the `cntinfo` tag

for element in tree.iter('cntinfo'):
    for child in element.getchildren():
        print "{0.tag}: {0.text}".format(child)

これは印刷されます:

cntorg: Atherton Tablelands GIS
cntpos: GIS Coordinator
address: PO Box 1616, 8 Tolga Rd
city: Atherton
state: QLD
country: AUSTRALIA
postal: 4883
cntvoice: 07 40918600
cntfax: 07 40917035
cntemail: info@atgis.com.au

同様に、ファイル内の他の要素をステップスルーできます。ただし、XSLTを使用することを強くお勧めします。


このスニペットは、xsltスタイルシートを使用してxmlドキュメントをcsvに変換します(この質問から):

# First, we load the stylesheet
with open(r'd:\test.xsl') as f:
    temp = etree.parse(f)
    style_sheet = etree.XSLT(temp)

# Apply it to the previously parsed document tree:
converted_xml = style_sheet(tree)

# Print the results:
str(converted_xml)

これはあなたに与えるでしょう:

'"",    "<>",    "ATGISTablelands Regional Council"\r"<>",    "EPSG",
  "GDA94GRS80Map Grid of AustraliaZone 55 (144E - 150E)"\r"2012",    "Completed"
\r"OngoingCompleted",    "As RequiredAs Required"\r"FileType:",    "Format:Size"
,    "Internal Use Only"\r"~TBC~",    "Metadata imported.L:\\Data_Admin\\Metadat
aGenerator\\trc_Metadata_Template.xml2012120615341400",    "~TBC~",    "~TBC~",
   "~TBC~",    "~TBC~"\r"Atherton Tablelands GIS",    "GIS Coordinator",    "PO
Box 1616, 8 Tolga Rd",    "Atherton",    "QLD",    "AUSTRALIA",    "4883",    "0
7 40918600",    "07 40917035",    "info@atgis.com.au"\r""\r'
于 2013-03-06T05:28:08.427 に答える
0

<anzmeta>はドキュメントのルートであるため、ルート タグ名自体ではなく、findその直接の子の 1 つ ( など) を試してください。citeinfo

于 2013-03-06T04:49:24.180 に答える