2012-01-30 35 views
5

--- Cập nhật 3: Tôi đã nhận tập lệnh để cập nhật dữ liệu bắt buộc vào tệp xml đã hoàn thành nhưng mã sau bị xóa khỏi tệp văn bản. Tại sao điều này? làm thế nào tôi có thể thay thế nó?Tìm và thay thế nhiều dòng trong tệp xml/văn bản bằng cách sử dụng python

<?xml version="1.0" encoding="utf-8"?><?xml-stylesheet type='text/xsl' href='ANZMeta.xsl'?> 

Mã hoạt động hiện tại (ngoại trừ các vấn đề nêu trên).

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

path=os.getcwd() 
arcpy.env.workspace = path 

FileList = arcpy.ListFeatureClasses() 
FileCount = len(FileList) 
zone="_Zone" 

for File in FileList: 
    FileDesc_obj = arcpy.Describe(File) 
    FileNm=FileDesc_obj.file 
    newMetaFile=FileNm+"_BaseMetadata.xml" 

    check_meta=os.listdir(path) 
    if FileNm+'.xml' in check_meta: 
     shutil.copy2(FileNm+'.xml', newMetaFile) 
    else: 
     shutil.copy2('L:\Data_Admin\QA\Metadata_python_toolset\Master_Metadata.xml', newMetaFile) 
    tree=et.parse(newMetaFile) 

    print "Processing: "+str(File) 

    for node in tree.findall('.//title'): 
     node.text = str(FileNm) 
    for node in tree.findall('.//northbc'): 
     node.text = str(FileDesc_obj.extent.YMax) 
    for node in tree.findall('.//southbc'): 
     node.text = str(FileDesc_obj.extent.YMin) 
    for node in tree.findall('.//westbc'): 
     node.text = str(FileDesc_obj.extent.XMin) 
    for node in tree.findall('.//eastbc'): 
     node.text = str(FileDesc_obj.extent.XMax)   
    for node in tree.findall('.//native/nondig/formname'): 
     node.text = str(os.getcwd()+"\\"+File) 
    for node in tree.findall('.//native/digform/formname'): 
     node.text = str(FileDesc_obj.featureType) 
    for node in tree.findall('.//avlform/nondig/formname'): 
     node.text = str(FileDesc_obj.extension) 
    for node in tree.findall('.//avlform/digform/formname'): 
     node.text = str(float(os.path.getsize(File))/int(1024))+" KB" 
    for node in tree.findall('.//theme'): 
     node.text = str(FileDesc_obj.spatialReference.name +" ; EPSG: "+str(FileDesc_obj.spatialReference.factoryCode)) 
    print node.text 
    projection_info=[] 
    Zone=FileDesc_obj.spatialReference.name 

    if "GCS" in str(FileDesc_obj.spatialReference.name): 
     projection_info=[FileDesc_obj.spatialReference.GCSName, FileDesc_obj.spatialReference.angularUnitName, FileDesc_obj.spatialReference.datumName, FileDesc_obj.spatialReference.spheroidName] 
     print "Geographic Coordinate system" 
    else: 
     projection_info=[FileDesc_obj.spatialReference.datumName, FileDesc_obj.spatialReference.spheroidName, FileDesc_obj.spatialReference.angularUnitName, Zone[Zone.rfind(zone)-3:]] 
     print "Projected Coordinate system" 
    x=0 
    for node in tree.findall('.//spdom'): 
     for node2 in node.findall('.//keyword'): 
      print node2.text 
      node2.text = str(projection_info[x]) 
      print node2.text 
      x=x+1 


    tree.write(newMetaFile) 

--- Cập nhật 1 & 2: Nhờ Aleyna Tôi có đoạn code cơ bản sau đây mà làm việc

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

CodeString=['northbc','southbc', '<nondig><formname>'] 

nondig='nondigital' 
path=os.getcwd() 
arcpy.env.workspace = path 
xmlfile = path+"\\test.xml" 

FileList = arcpy.ListFeatureClasses() 
FileCount = len(FileList) 

for File in FileList: 
    FileDesc_obj = arcpy.Describe(File) 
    FileNm=FileDesc_obj.file 
    newMetaFile=FileNm+"_Metadata.xml" 
    shutil.copy2('L:\Data_Admin\QA\Metadata_python_toolset\Master_Metadata.xml', newMetaFile) 
    tree=et.parse(newMetaFile) 

    for node in tree.findall('.//northbc'): 
     node.text = str(FileDesc_obj.extent.YMax) 
    for node in tree.findall('.//southbc'): 
     node.text = str(FileDesc_obj.extent.YMin) 
    for node in tree.findall('.//westbc'): 
     node.text = str(FileDesc_obj.extent.XMin) 
    for node in tree.findall('.//eastbc'): 
     node.text = str(FileDesc_obj.extent.XMax)   
    for node in tree.findall('.//native/nondig/formname'): 
     node.text = nondig 

    tree.write(newMetaFile) 

Vấn đề là với giao dịch với mã xml như

- <spdom> 
    <keyword thesaurus="">GDA94</keyword> 
    <keyword thesaurus="">GRS80</keyword> 
    <keyword thesaurus="">Transverse Mercator</keyword> 
    <keyword thesaurus="">Zone 55 (144E - 150E)</keyword> 
    </spdom> 

Vì các từ khóa ... không phải là duy nhất trong số <spdom>, chúng tôi có thể cập nhật những thứ này theo thứ tự từ các giá trị đến từ

FileDesc_obj.spatialReference.name 

u'GCS_GDA_1994'

--- POST ORIGINAL ---

Tôi đang xây dựng một chương trình để tạo ra các file xml siêu dữ liệu từ các tập tin không gian trong thư viện của chúng tôi. Tôi đã tạo các kịch bản để trích xuất dữ liệu không gian và dữ liệu cần thiết từ các tệp và tạo một tệp chỉ mục dựa trên shp và tệp văn bản nhưng bây giờ tôi muốn ghi thông tin này vào tệp siêu dữ liệu xml cơ sở được ghi vào tiêu chuẩn anzlic bằng cách thay thế các giá trị nắm giữ bởi các yếu tố chung/tĩnh ...

vì vậy, ví dụ tôi muốn thay thế mã xml sau

<northbc>8097970</northbc> 
<southbc>8078568</southbc> 

với

<northbc> GeneratedValue_[desc.extent.XMax] /<northbc> 
<southbc> GeneratedValue_[desc.extent.XMax] </southbc> 

vấn đề là rằng rõ ràng là số lượng/giá trị giữa và sẽ không giống nhau.

Tương tự đối với thẻ xml như <title>, <nondig><formname> v.v ... trong ví dụ sau, cả hai thẻ phải được tìm kiếm cùng nhau dưới dạng tên biểu mẫu xuất hiện nhiều lần (không phải là duy nhất).

Tôi đang sử dụng Python Regular Expression thủ [ở đây] [1],

+1

Xem http://stackoverflow.com/a/1732454/383402 – Borealid

+0

cảm ơn ... Tôi không cố gắng viết một tệp xml từ đầu. Tôi chỉ muốn thay thế khối văn bản trong các thuộc tính đã cho dựa trên đầu vào từ mô-đun arcpy. – GeorgeC

+1

Vì vậy, khi nó tạo ra đầu ra trông giống như ' 8097970 ', regex của bạn sẽ xử lý nó? – Borealid

Trả lời

2

Sử dụng (các) thẻ đã cho ở trên:

import os 
import xml 
from xml.etree import ElementTree as et 
path = r"/your/path/to/xml.file" 
tree = et.parse(path) 
for node in tree.findall('.//northbc'): 
    node.text = "New Value" 
tree.write(path) 

Ở đây, XPATH .//northbc trả về tất cả các nút 'bắcbc' trong tài liệu XML. Bạn có thể điều chỉnh mã cho nhu cầu của mình một cách dễ dàng.

+0

Cảm ơn nhưng tôi nhận được thông tin sau ... >> path = os.getcwd() >> tree = et.parse (đường dẫn) Traceback (cuộc gọi gần đây nhất): Tệp "C: \ Program Files (x86) \ Wing IDE 101 4.0 \ src \ debug \ tserver \ _sandbox.py", dòng 1, trong # Được sử dụng trong nội bộ để gỡ lỗi hộp cát bên dưới trình thông dịch bên ngoài Tệp "C: \ Python26 \ ArcGIS10.0 \ Lib \ xml \ etree \ ElementTree.py", dòng 862, phân tích cú pháp tree.parse (nguồn, phân tích cú pháp) Tệp "C: \ Python26 \ ArcGIS10.0 \ Lib \ xml \ etree \ ElementTree.py ", dòng 579, trong phân tích cú pháp nguồn = mở (nguồn," rb ") IOError: [ Errno 13] Quyền bị từ chối: 'L: \\ Dữ liệu_Admin \\ QA \\ Metadata_python_toolset \\ training' – GeorgeC

+0

Vui lòng DISREGARD nhận xét trước của tôi. Nó hoạt động tốt khi đường dẫn là một tập tin xml thực tế. Bạn sẽ làm gì với các thẻ lặp lại như ví dụ thứ 3 - '' trong đó tên biểu mẫu được lặp lại nhưng nondig là duy nhất. – GeorgeC

+0

Nếu tôi làm đúng, bạn có nhiều số s là con trực tiếp của các nút độc đáo? Sau đó, bạn có thể sử dụng một xpath như vậy .//nondig/formname để nhận được s. Bạn có thể nháy lên trên cây và kiểm tra cha mẹ trước khi thay thế giá trị hoặc thậm chí tốt hơn bạn có thể viết lại xpath của bạn bằng cách sử dụng attr duy nhất của cha mẹ (có lẽ là id?) Sao cho s sẽ được nhóm theo s. – Aleyna

0

tôi có thể được nêu rõ ràng ở đây, nhưng cậu xem xét sử dụng một cây DOM để phân tích và thao tác XML của bạn?

1

Nếu bạn đang xử lý XML hợp lệ, hãy sử dụng XPath để tìm các nút ưa thích và nút ElementTree api để thao tác nút.

Ví dụ: xpath của bạn có thể giống như '// northbc' và bạn chỉ thay thế nút văn bản bên trong nó.

Xem http://docs.python.org/library/xml.etree.elementtree.html cũng như http://pypi.python.org/pypi/lxml/2.2.8 cho hai thư viện khác nhau sẽ giúp bạn thực hiện việc này.Tìm kiếm google cho XPath và xem hướng dẫn w3c cho phần giới thiệu phong nha cho XPath (tôi dường như không thể đăng nhiều hơn hai liên kết trong một bài đăng hoặc tôi cũng muốn liên kết nó)

+0

cảm ơn. Điều này dường như đi đúng hướng và tôi chỉ trải qua http://www.w3schools.com/xpath/ – GeorgeC

Các vấn đề liên quan