-->

Updating XML with namespace with xmlstarlet 1.6.1

2019-07-16 14:15发布

问题:

I am trying to update the host-slave.xml from a Wildfly Cluster configuration with xmlstarlet.

I am using the following statement:

xml ed -N my=urn:jboss:domain:2.2 -u "_:host/management/security-realms/security-realm[@name='UndertowRealm']/server-identities/ssl/keystore/@path" -v "test" Wildfly\wildfly-8.2.0.Final\WildFly-HOST\configuration\host-slave.xml

The namespace definition in xml:

<host name="172.16.1.11" xmlns="urn:jboss:domain:2.2" >

The part of the xml I want to change:

<security-realm name="UndertowRealm">  
    <server-identities>  
        <ssl>  
            <keystore path="D:\wildfly-8.2.0.Final\ssl\wildfly.keystore"  keystore-password="rsaddbTsadYvvMXZ" alias="wildfly"  /> 
        </ssl>  
    </server-identities>  
</security-realm>

But if I delete the namespace defition from the xml, and use the following statement:

xml ed -u ":host/management/security-realms/security-realm[@name='UndertowRealm']/server-identities/ssl/keystore/@path" -v "test" Wildfly\wildfly-8.2.0.Final\WildFly-HOST\configuration\host-slave.xml

It works as expected, so it is not an Issue with XPATH. As I dont know what happens to wildfly if I delete the namespace declaration, I would like to keep it.

回答1:

The problem is that you need to use the declared prefix (my, which you correctly mapped to the default namespace URI) to reference element in that namespace in your XPath, for example :

/my:security-realm[@name='UndertowRealm']/my:server-identities/my:ssl/my:keystore/@path

Basically, all element without prefix, within element where default namespace is declared, are considered in the same default namespace, hence need to be referenced using the prefix my.



回答2:

Starting with version 1.2.1 you can use de default namespace _
(drop the -N argument)

xml ed -u "/_:security-realm[@name='UndertowRealm']/_:server-identities/_:ssl/_:keystore/@path" -v "test" Wildfly\wildfly-8.2.0.Final\WildFly-HOST\configuration\host-slave.xml

As explained here:

1.3. A More Convenient Solution

XML documents can also use different namespace prefixes, on any element in the document. In order to handle namespaces with greater ease, XMLStarlet (versions 1.2.1+) will use the namespace prefixes declared on the root element of the input document. The default namespace will be bound to the prefixes "_" and "DEFAULT" (in versions 1.5.0+).