繁体   English   中英

如何提取XML文件标签中的值?

[英]how we can extract a value in a tag of a XML file?

我想读取一个weblogic.xml并提取上下文根信息。 这是一个例子:

<?xml version="1.0" encoding="ISO-8859-1"?>
<!DOCTYPE weblogic-web-app PUBLIC "-//BEA Systems, Inc.//DTD Web Application 8.1//EN" "http://www.bea.com/servers/wls810/dtd/weblogic810-web-jar.dtd">
 <weblogic-web-app>
   <context-root>
    /XYZ
   </context-root>
 </weblogic-web-app>

我已经尝试了以下命令

sed -n '/context-root/{s/.*<context-root>//;s/<\/context-root.*//;p;}' weblogic.xml

awk -F "[><]" '/context-root/{print $3}' weblogic.xml

perl -ne 'if (/context-root/){ s/.*?>//; s/<.*//;print;}' weblogic.xml

如果标签如下所示,则可以正常工作:

<context-root>/XYZ</context-root>

如何从上述xml中提取标签的值?

awk '{ gsub(/^[ \t]+|[ \t\r]+$/, ""); } /<\/context-root>/ { p = 0 }; p; /<context-root>/ { p = 1 }' file

输出:

/XYZ

更新资料

#!/usr/bin/awk -f
{
    gsub(/^[ \t]+|[ \t\r]+$/, "")
}
match($0, /^[^<]*<\/context-root>/) {
    if (p) {
        t = substr($0, 1, index($0, "</context-root>") - 1)
        if (length(t)) print t
    }
    $0 = substr($0, RSTART + RLENGTH)
    p = 0
}
{
    while (match($0, /<context-root>[^<]*<\/context-root>/)) {
        t = substr($0, RSTART, RLENGTH)
        gsub(/<\/?context-root>/, "", t)
        print t
        $0 = substr($0, RSTART + RLENGTH)
    } 
}
p
match($0, /<context-root>/) {
    t = substr($0, RSTART + RLENGTH)
    if (length(t)) print t
    p = 1
}

另一个版本:

#!/usr/bin/awk -f
function strip(t) {
    gsub(/^[ \t]+|[ \t\r]+$/, "", t)
    return t
}
match($0, /^[^<]*<\/context-root>/) {
    if (p) {
        t = strip(substr($0, 1, index($0, "</context-root>") - 1))
        if (length(t)) print t
    }
    $0 = substr($0, RSTART + RLENGTH)
    p = 0
}
{
    while (match($0, /<context-root>[^<]*<\/context-root>/)) {
        t = substr($0, RSTART, RLENGTH)
        gsub(/<\/?context-root>/, "", t)
        if (length(t)) print t
        $0 = substr($0, RSTART + RLENGTH)
    } 
}
p {
    print strip($0)
}
match($0, /<context-root>/) {
    t = strip(substr($0, RSTART + RLENGTH))
    if (length(t)) print t
    p = 1
}

输入:

    <context-root>
        A B
    </context-root>
    <context-root>C D</context-root><context-root>E F</context-root><context-root>G H
    I J</context-root>

输出:

A B
C D
E F
G H
I J

暂无
暂无

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

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