Find element with attribute with minidom

前端 未结 3 2236
梦毁少年i
梦毁少年i 2021-02-15 10:07

Given



        
3条回答
  •  梦如初夏
    2021-02-15 10:41

    I don't think you can.

    From the parent element, you need to

    for subelement in element.GetElementsByTagName("field"):
        if subelement.hasAttribute("frame.len"):
            do_something()
    

    Reacting to your comment from March 11, if the structure of your documents is stable and free of nasty surprises (like angle brackets inside attributes), you might want to try the unthinkable and use a regular expression. This is not recommended practice but could work and be much easier than actually parsing the file. I admit that I've done that sometimes myself. Haven't gone blind yet.

    So in your case you could (assuming that a tag doesn't span multiple lines):

    xmlfile = open("myfile.xml")
    for line in xmlfile:
        match = re.search(r']+)/>', line):
        if match:
            result = match.group(1)
            do_something(result)
    

    If a tag can span multiple lines, you could try loading the entire file as plain text into memory and then scan it for matches:

    filedump = open("myfile.xml").read()
    for match in re.finditer(r']+)/>', filedump):
        result = match.group(1)
        do_something(result)
    

    In both cases, result will contain the attributes other than frame.len. The regex assumes that frame.len is always the first attribute inside the tag.

提交回复
热议问题