How to find and replace an attribute value in a XML

后端 未结 3 579
盖世英雄少女心
盖世英雄少女心 2021-01-02 09:01

I am building a \"XML scanner\" in Java that finds attribute values starting with \"!Here:\". The attribute value contains instructions to replace later. for example I hav

3条回答
  •  攒了一身酷
    2021-01-02 09:20

    Gounelle's answer is correct, however, it is based on fact that you know attribute name in advance.

    If you want to find all attributes based only on their value, use this expression for xpath:

    NodeList attributes = (NodeList) xpath.evaluate(
        "//*/@*[contains(. , '!Here')]",
         doc, 
        XPathConstants.NODESET
    )
    

    Here, you select all attributes by setting //*/@*. Then you can set a condition like I mentioned above.

    By the way, if you search for a single attribute, you can use Attr instead of Node

    Attr attribute = (Attr) xpath.evaluate(
        "//*/@*[contains(. , '!Here')]",
         doc, 
        XPathConstants.NODE
    )
    
    attribute.setValue("What!");
    

    If you want to find attributes by particular value, use

    "//*/@*[ . = '!Here:String:HashKey' ]"
    

    If you search for attribute using number comparison, for instance, if you had

    
    
    

    then you could select second bean by setting expression to

    "//*/@*[ . > 1000]"
    

提交回复
热议问题