xml: скопировать строку текста из одного элемента в другой? [закрыто]

спасибо за помощь. Я не программист, но понимаю основные принципы. мне нужно сделать это в кучу файлов xml. Я уверен, что xpath pl или xtask или какая-то комбинация с использованием регулярного выражения может справиться с этим, но я потерялся. У кого-нибудь есть какие-либо идеи? Благодарность!

Вот область:

Скопируйте из элемента «scc_title» в элемент «scc_comments». Элемент scc_comments обычно пуст. если это не так, мне все равно нужно добавить его к текущему содержимому.

<property name="scc_title" type="s">NEED TO COPY THIS TEXT</property>

<property name="scc_comments" type="s">AND PASTE IT HERE</property>
1
задан 26 February 2014 в 02:22

2 ответа

Альтернативный путь с python и ElementTree:

from __future__ import print_function
import sys 
import xml.etree.ElementTree as ET

def main():
  if len(sys.argv) < 3:
    print("usage:", sys.argv[0], "input", "output")
    sys.exit(1)
  tree = ET.parse(sys.argv[1])
  root = tree.getroot();
  src = root.find(".//*[@name='scc_title']")
  dst = root.find(".//*[@name='scc_comments']")
  if src is not None and dst is not None:
    dst.text += src.text
    tree.write(sys.argv[2])
  else:
    if src is None:
      print("Failed to find 'scc_title' attribute", file=sys.stderr)
    if dst is None:
      print("Failed to find 'scc_comments' attribute", file=sys.stderr)
    sys.exit(1)

if __name__ == "__main__":
  main()
2
ответ дан 26 February 2014 в 02:22

Pythonic не xml способ предположить, что scc_title прибывает прежде scc_comments И каждый тег, имеет свою собственную строку И что все XML-файлы находятся в том же каталоге , я не протестировал это , но это - основная идея. Кроме того, я не уверен, существует ли быстрый GUI путь, и я не программист ни один, таким образом, существует, вероятно, лучший способ сделать это с xml модулями:

#put this in the directory with the xml files
import re
import os

#for file_name in current directory "."
for file_name in os.listdir("."):

    if ".xml" in file_name:
        outfile = open("edited_"+file_name,"w+")

        with open(file_name,'r') as f:
            for line in f:

                if "scc_title" in line:
                    #split the string by two delimeters "<" and ">" and get the 3rd element starts at 0
                    scc_title_value = re.split('<|>',line)[2]

                if "scc_comments" in line:
                    scc_comments_value = re.split('<|>',line)[2]
                    #replace scc_comments_value with scc_title_value
                    line = line.replace(scc_comments_value,scc_title_value)

                outfile.write(line)
0
ответ дан 26 February 2014 в 02:22

Другие вопросы по тегам:

Похожие вопросы: