Home > Net >  Adding new attribute to existing xml file using sed
Adding new attribute to existing xml file using sed

Time:08-11

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.....

CodePudding user response:

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

CodePudding user response:

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>
  • Related