使用python替换xml文件中的兄弟节点

时间:2012-08-23 20:39:25

标签: python xml replace find siblings

我想要一种在YAMJ的xml文件中改变观看电影状态的方法。我可以提供baseFilenameBase,fileLocation和fileURL。我想将两个观看的元素改为真。

<library count="1">
   <category count="1" current="true" name="Other">
      <index </index>
   </category>
   <movies cols="18" count="18" indexCount="673" totalCount="737">
      <movie isExtra="false" isSet="false" isTV="false">
         <baseFilenameBase>FILE NAME</baseFilenameBase>
         <watched>false</watched>
         <files>
            <file firstPart="1" lastPart="1" season="-1" size="0" subtitlesExchange="NO"
                  title="UNKNOWN"
                  watched="false"
                  zcd="2">
               <fileLocation>PATH TO FILE</fileLocation>
               <fileURL>PATH TO FILE</fileURL>
            </file>
         </files>
      </movie>
      <movie

      And repeats .....
    </movies>
</library>    

我已经设法替换其他xml文件中的监视dy正在执行

                doc = parse(file)
                node = doc.getElementsByTagName('watched')
                node[0].firstChild.nodeValue = 'true'    

与试图与兄弟姐妹/邻居交往相比,这非常简单

4 个答案:

答案 0 :(得分:0)

以下内容将在所有电影和文件中设置为true,您应该将其调整为仅更改所需的内容,并将movies.xml更改为文件名。

from xml.etree import ElementTree

tree = ElementTree.parse('movies.xml')

for movie in tree.findall('movies/movie'):
    movie.find('watched').text = 'true'
    for mfile in movie.findall('files/file'):
        mfile.set('watched', 'true')

tree.write('movies.xml')

答案 1 :(得分:0)

                msg = 'Starting xml update in '.format(updatexmlwatched)
            Debug(msg)
            pchtrakt.logger.info(msg)
            if pchtrakt.isMovie:
                xmlpath = updatexmlwatched + "Other*.xml"
                for name in glob.glob(xmlpath):
                    if myMedia.oStatus.fileName[:-4] in open(name).read():#gets xml file name as name
                        tree = ElementTree.parse(name)
                        for movie in tree.findall('movies/movie'):
                            if movie.find('baseFilenameBase').text == myMedia.oStatus.fileName[:-4]:#for  content in penContents:
                                movie.find('watched').text = 'true'
                                for mfile in movie.findall('files/file'):
                                    mfile.set('watched', 'true')
                                    bak_name = name[:-4]+'.bak'
                                    tree.write(bak_name)
                                    os.rename(bak_name, name)
                                    txt = name.replace(updatexmlwatched, '') + ' has been modified as watched for ' + myMedia.oStatus.fileName
                                    Debug(txt)
                                    pchtrakt.logger.info(txt)
                                    break
            elif pchtrakt.isTvShow:
                a = re.split("([-|.]*[Ss]\\d\\d[Ee]\\d\\d.)", myMedia.oStatus.fileName)
                ep_name = a[2][:-4].replace(".", " ").replace("- ", "")
                season_xml = a[0][:-3].replace(".", " ").replace(" - ", "")
                f_size = str(os.path.getsize(myMedia.oStatus.fullPath))
                ep_no = '01'
                fileinfo = updatexmlwatched + "Set_" + season_xml + "*.xml"
                for name in glob.glob(fileinfo):
                    if myMedia.oStatus.fileName in open(name).read():
                        tree = ElementTree.parse(name)
                        for movie in tree.findall('*/movie/files/file'):
                            if movie.get('firstPart') == str(myMedia.parsedInfo.episode_numbers[myMedia.idxEpisode]) and movie.get('season') == str(myMedia.parsedInfo.season_number):
                                movie.set('watched', 'true')
                                bak_name = name[:-4]+'.bak'
                                tree.write(bak_name)
                                os.rename(bak_name, name)
                                txt = name.replace(updatexmlwatched, '') + ' has been modified as watched for ' + myMedia.oStatus.fileName
                                Debug(txt)
                                pchtrakt.logger.info(txt)
                                break
                fileinfo = updatexmlwatched + "Other*.xml"
                for name in glob.glob(fileinfo):
                    if myMedia.oStatus.fileName in open(name).read():
                        tree = ElementTree.parse(name)
                        for movie in tree.findall('*/movie/files/file'):
                            if movie.get('size') == f_size and movie.get('firstPart') == str(myMedia.parsedInfo.episode_numbers[myMedia.idxEpisode]) and movie.get('season') == str(myMedia.parsedInfo.season_number):
                                movie.set('watched', 'true')
                                bak_name = name[:-4]+'.bak'
                                tree.write(bak_name)
                                os.rename(bak_name, name)
                                txt = name.replace(updatexmlwatched, '') + ' has been modified as watched for ' + myMedia.oStatus.fileName
                                Debug(txt)
                                pchtrakt.logger.info(txt)
                                break

这就是我最终的结果。它确实有效,但如果xml位于网络共享上,有时会导致媒体播放。我相信它正在搜索包含变量的xml。在低功耗媒体播放器上运行时,是否有更少的系统饥饿方式。

由于

答案 2 :(得分:0)

如果您在小型媒体服务器上运行它可能有sed,那么python可能不是答案。

sed -i 's/<watched>false/<watched>true/g' movies.xml

只需检查您sed的{​​{1}}版本,以便了解可用的选项。

答案 3 :(得分:0)

假设你的baseFilenameBase是唯一的,一个简单的方法如下:我无法评论,所以我不能将它添加到sp的答案。

魔术是xpath表达式“// movie [baseFilenameBase / text()='PATHHERE']”这是一个xpath表达式,表示:

  • // movie - 查找所有电影节点
  • [条件] - 条件为真的情况
  • baseFilenameBase / text()='PATHHERE' - 一个条件,说它必须有一个baseFilenameBase节点,包含文本'PATHHERE'

然后我使用format将path变量的内容放入。 XPath是一个很好的语法,用于引用xml节点check here for more infomation

P.S。我必须承认我没有这样做。但我不认为有任何语法错误,它应该可以工作。

from xml.etree import ElementTree

tree = ElementTree.parse('movies.xml')
movie = tree.find("//movie[baseFilenameBase/text() = '{}']".format(path))
movie.find('watched').text = 'true'
for file in movie.find('files').findall('file')
    file.set("watched", 'true')

tree.write('movies.xml')