简体   繁体   English

使用 shell 脚本读取属性文件并插入 xml 标记

[英]Read property file and Insert xml tag using shell script

I Have a property file as below,我有一个如下的属性文件,

Name=sample
TagName=Test1
TagType=P

Name=sample1
TagName=Test2
TagType=Y

I have a xml file as below,我有一个 xml 文件如下,

 <?xml version="1.0" encoding="UTF-8"?>
  <root>
  </root>

Need to append as below,需要 append 如下,

   <?xml version="1.0" encoding="UTF-8"?>
  <root>
    <sub>
      <TagName>Test1</TagName>
      <TagType>P</TagType>
    </sub>
    <sub>
      <TagName>Test2</TagName>
     <TagType>Y</TagType>
    </sub>
  </root>

Can any one help me to insert in xml file using sed or awk command in shell script...谁能帮我在 xml 文件中使用 sed 或 awk 命令在 Z2591C948B701119FE6...

Thanks in Advance..提前致谢..

With bash and xmlstarlet .使用bashxmlstarlet I removed the space before <?xml in your xml file.我在您的 xml 文件中删除了<?xml之前的空格。

#!/bin/bash

file="file.xml"
prop="property.txt"

while IFS="=" read -r key value; do
  [[ "$key" == "Name" ]]    && xmlstarlet edit -L --subnode '//root'             --type elem -n "sub" "$file"
  [[ "$key" == "TagName" ]] && xmlstarlet edit -L --subnode '//root/sub[last()]' --type elem -n "TagName" --value "$value" "$file"
  [[ "$key" == "TagType" ]] && xmlstarlet edit -L --subnode '//root/sub[last()]' --type elem -n "TagType" --value "$value" "$file"
done < "$prop"

Output to file.xml: Output 到文件。xml:

<?xml version="1.0" encoding="UTF-8"?>
<root>
  <sub>
    <TagName>Test1</TagName>
    <TagType>P</TagType>
  </sub>
  <sub>
    <TagName>Test2</TagName>
    <TagType>Y</TagType>
  </sub>
</root>

See: xmlstarlet edit for a quick syntax overview.请参阅: xmlstarlet edit以获得快速的语法概述。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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