正确打印xml标签

时间:2014-06-11 12:46:10

标签: python

<?xml version="1.0" encoding="utf8"?>
 <Test xmlns="http://schemas.microsoft.com/developer/build/2003">
 <Group>
 <Project Include="Name">    
      <Node1>true</Node1>
      <Node2>true</Node2>
      <Node3>false</Node3>
      <Node4>D3A4E4D9-C9E4-4f31-A225-E10A48AA5E10</Node4>
      <Node5>D3A4E4D9-C9E4-4f31-A225-E10A48AA5E10</Node5>
      <Node6>C6311C26-274C-40ea-8DF8-34F80F00DED3</Node6>
      <Node7>C6311C26-274C-40ea-8DF8-34F80F00DED3</Node7>
      <Node8>128</Node8>
      <Node9>128</Node9>
      <Node10>1000</Node10>
      <Node11>255</Node11>
      <Node12>0</Node12>
      <Node13>128</Node13>
      <Node14>007</Node14>

  </Project>
 </Group>

我有一个上面给出的xml文件。我想得到项目节点下所有节点的标签和文本。我写了下面的代码来获取节点和文本值。但是它没有工作

tree = ElementTree(file= filename)
root = tree.getroot()
for Group in root:
for Project in Group:
    for child in Project:
        print child.tag,child.text

但是当我打印iam时,输出如下所示。如何从输出中删除{http://schemas.microsoft.com/developer/build/2003}

{http://schemas.microsoft.com/developer/build/2003}Node1 true
{http://schemas.microsoft.com/developer/build/2003}Node2 false
{http://schemas.microsoft.com/developer/build/2003}Node3 D3A4E4D9-C9E4-4f31-A225-   E10A48AA5E10
{http://schemas.microsoft.com/developer/build/2003}Node4 D3A4E4D9C9E44f31A225E10A48AA5E10
{http://schemas.microsoft.com/developer/build/2003}Node5 C6311C26-274C-40ea-8DF8-34F80F00DED3
{http://schemas.microsoft.com/developer/build/2003}Node6 C6311C26-274C-40ea-8DF8-34F80F00DED
{http://schemas.microsoft.com/developer/build/2003}Node7 128
{http://schemas.microsoft.com/developer/build/2003}Node8 128
{http://schemas.microsoft.com/developer/build/2003}Node9 1000
{http://schemas.microsoft.com/developer/build/2003}Node10 255
{http://schemas.microsoft.com/developer/build/2003}Node11 0
{http://schemas.microsoft.com/developer/build/2003}Node12 128
{http://schemas.microsoft.com/developer/build/2003}Node13 007

1 个答案:

答案 0 :(得分:1)

将名称拆分为}并取最后一部分。

tree = ElementTree(file=filename)
root = tree.getroot()
for Group in root:
    for Project in Group:
        for child in Project:
            print child.tag.split('}')[-1], child.text

输出:

Node1 true
Node2 true
Node3 false
Node4 D3A4E4D9-C9E4-4f31-A225-E10A48AA5E10
Node5 D3A4E4D9-C9E4-4f31-A225-E10A48AA5E10
Node6 C6311C26-274C-40ea-8DF8-34F80F00DED3
Node7 C6311C26-274C-40ea-8DF8-34F80F00DED3
Node8 128
Node9 128
Node10 1000
Node11 255
Node12 0
Node13 128
Node14 007