Do not do this with sed; it will break horribly when benign formatting changes happen to the XML.
Use a proper XML-parsing tool. For example with xmlstarlet:
xmlstarlet sel -t -c '//Server[IpAddress="a.b.c.d"]/Name/node()' -n filename.xml
or with xmllint:
xmllint --xpath '//Server[IpAddress="a.b.c.d"]/Name/node()' filename.xml
or with old versions of xmllint that don't yet understand --xpath
(if you are tempted to use this I encourage you to look at other tools):
echo 'cat //Server[IpAddress="a.b.c.d"]/Name/node()' | xmllint --shell filename.xml | sed '1d;$d'
or with the xpath
utility from the XML::XPath
Perl library:
xpath -q -e '//Server[IpAddress="a.b.c.d"]/Name/node()' filename.xml
...or with any of three dozen (dozen) other XML tools.
The heart of this is the XPath expression //Server[IpAddress="a.b.c.d"]/Name/node()
. This consists of:
//Server
refers to a Server
node anywhere in the document
//Server/Name
refers to a Name
node that is the child of such a Server
node
//Server/Name/node()
refers to the contents of such a Name
node
//Server[IpAddress="a.b.c.d"]
refers to a server node that satisfies the condition IpAddress="a.b.c.d"
, which means that it has a child IpAddress
node that contains a.b.c.d
Putting all that together, //Server[IpAddress="a.b.c.d"]/Name/node()
refers to the contents of a Name
node that is the child of a Server
node anywhere in the document that has an IpAddress
child node that contains a.b.c.d
.