简体   繁体   中英

Adding new attribute to existing xml file using sed

I am trying to add attribute under an existing attribute in an XML file. I have been using sed for edit but never used it for update. Would be helpful is someone tell how to add a new attr and an element under that new attrb -

Current xml

<?xml version='1.0' encoding='UTF-8'?>
<logging_configuration>
 <log_handlers>
  <log_handler name='console-handler' class='oracle.core.ojdl.logging.ConsoleHandler' level='SEVERE' formatter='oracle.core.ojdl.weblogic.ConsoleFormatter'/>

    // add new tag
 </log_handlers>
 </logging_configuration>

After updated, need to added new attribute of tag.

<?xml version='1.0' encoding='UTF-8'?>
<logging_configuration>
 <log_handlers>
  <log_handler name='console-handler' class='oracle.core.ojdl.logging.ConsoleHandler' level='SEVERE' formatter='oracle.core.ojdl.weblogic.ConsoleFormatter'/>

<log_handler name='coherence-console-handler' class='oracle.core.ojdl.logging.ConsoleHandler' level='FINER' formatter='oracle.core.ojdl.weblogic.ConsoleFormatter'/>
 </log_handlers>
 </logging_configuration>

Can you help me this, below code try but not added the new tag.

log_handler_coherence="<log_handler name='coherence-console-handler' class='oracle.core.ojdl.logging.ConsoleHandler' level='FINER' formatter='oracle.core.ojdl.weblogic.ConsoleFormatter'/>"

C=$(echo $log_handler_coherence | sed 's/\//\\\//g')

sed "/<\/log_handlers>/ s/.*/${C}\n&/" $file


But it's not updating.....

For python (very basic, rest for you):

from xml.dom.minidom import parse
import xml.dom.minidom

doc = xml.dom.minidom.parse("file.xml")
log_handlers = doc.getElementsByTagName("log_handlers")
newHandler = doc.createElement("log_handler")
newHandler.setAttribute("name","coherence-console-handler");
# more attrs
log_handlers[0].appendChild(newHandler)
print(doc.toprettyxml())

https://docs.python.org/3/library/xml.dom.minidom.html

Using sed

$ log_handler_coherence="<log_handler name='coherence-console-handler' class='oracle.core.ojdl.logging.ConsoleHandler' level='FINER' formatter='oracle.core.ojdl.weblogic.ConsoleFormatter'/>"
$ sed "\~/log_handlers~s~^~$log_handler_coherence\n~" input_file
<?xml version='1.0' encoding='UTF-8'?>
<logging_configuration>
 <log_handlers>
  <log_handler name='console-handler' class='oracle.core.ojdl.logging.ConsoleHandler' level='SEVERE' formatter='oracle.core.ojdl.weblogic.ConsoleFormatter'/>

<log_handler name='coherence-console-handler' class='oracle.core.ojdl.logging.ConsoleHandler' level='FINER' formatter='oracle.core.ojdl.weblogic.ConsoleFormatter'/>
 </log_handlers>
 </logging_configuration>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM