在XML文件中找到一行,然后使用python将下一行替换为其他内容

时间:2019-02-05 13:32:14

标签: python shell search replace

使用python我需要在上述行匹配时替换XML文件中的行。

#include <stdlib.h>
#include <stdio.h>
#include <string.h>

typedef struct
    {
        char *data;
        size_t length;
    } kstring;

kstring name;
char *kstring_init = "blabla";

void kstrextend(kstring *strp, size_t nbytes)
{
    char *nwData;

    size_t lnth = strp->length;

    if ((int) lnth >= (int) nbytes) {
        printf("Error, size already larger than requested size.\n");
        exit(-1);
    }

    // new array allocate with large size and copy data to new array
    nwData = realloc(strp->data, sizeof(char) * (int) nbytes);
    if(nwData == NULL)
    {
        printf("Error, realloc returned NULL\n");
        exit(-1);
    }

    //Making strp->data point to the new array
    strp->data = nwData;
    //Setting strp->length to the new size.
    strp->length = nbytes;

    for(int i = 0; i < lnth; i++)
    {
        printf("\n %c", strp->data[i]);
    }
    // filled with '\0' in remaining space of new array
    for (int lp = lnth; lp < (int) nbytes; lp++)
    {
        strp->data[lp] = '\0';
        printf("\n %c", strp->data[lp]);
    }
}

int main(void)
{
    size_t a;

    printf("\n Enter number: ");
    scanf("%d", &a);

    name.length = strlen(kstring_init) + 1;
    printf("Length of string is: %d\n", name.length);
    name.data = (char*)malloc(sizeof(char) * name.length);
    strcpy(name.data, kstring_init);

    printf("Old string: %s\n", name.data);
    printf("You want to reallocate %d bytes\n", a);

    kstrextend(&name, a);

    return 0;
}

在这里我要搜索 <groupId>test</groupId> <artifactId>dmrfolder</artifactId> <version>1.0</version> (如果找到),那么我需要用dmrfolder替换下面的1.0

我遵循以下方法,但对我而言无效。

somevalue

预期结果将

with open('test.xml', 'r') as file :
            data = file.read()
            fnl = data.replace(line[1], str)
            with open('test.xml', 'w') as fw:
               fw.write(fnl)
               fw.close()

2 个答案:

答案 0 :(得分:0)

您可以使用lxmlgetnext()通过以下方式修改每个artifactId元素的直接同级值:

import lxml.etree

xml = """
<xml>
  <groupId>test</groupId>
  <artifactId>dmrfolder</artifactId>
  <version>1.0</version>
</xml>
"""

root = lxml.etree.fromstring(xml)
for e in root.findall("artifactId"):
    e.getnext().text = "somevalue"

print(lxml.etree.tostring(root, encoding="unicode"))

结果:

<xml>
  <groupId>test</groupId>
  <artifactId>dmrfolder</artifactId>
  <version>somevalue</version>
</xml>

答案 1 :(得分:0)

如果数据文件格式与发布的格式完全相同(包括间距),则可以使用.replace()

        fnl = data.replace('''dmrfolder</artifactId>
    <version>1.0''', '''dmrfolder</artifactId>
    <version>somevalue''')

对于可变或未知格式,可以使用re.sub()

        fnl = re.sub('(dmrfolder</artifactId>\s*<version>)1.0', r'\1somevalue', data)
  • \s-任何空格字符,包括\n
  • \1-第一个(这里:唯一的)带括号的组