How can I save an XML document using awk, Perl or Python?

I have an XML file with the following data format:

<net NetName="abc" attr1="123" attr2="234" attr3="345".../>
<net NetName="cde" attr1="456" attr2="567" attr3="678".../>
....

Can someone tell me how I could pass data to an XML file using single-line awk? For example, I would like to know attr3 from abc. He will return me 345.

+3
source share
5 answers

In general, you are not . Parsing XML / HTML is quite complicated without trying to do it briefly, and although you can hack a solution that succeeds with a limited subset of XML, it will eventually break.

, XML-, , ?

, XML- awk, , XML awk, " ", ". , , , , - Perl, XML:: Simple ( ) - XML.

, , , XML. XML , :

<netlist>
  <net NetName="abc" attr1="123" attr2="234" attr3="345".../>
  <net NetName="cde" attr1="456" attr2="567" attr3="678".../>
  ....
</netlist>

, XML , XML , , awk one-liner, "" "XML", XML .

, Perl script, :

#!/usr/bin/perl

use strict;
use warnings;
use XML::Simple;

sub usage {
  die "Usage: $0 [NetName] ([attr])\n";
}

my $file = XMLin("file.xml", KeyAttr => { net => 'NetName' });

usage() if @ARGV == 0;

exists $file->{net}{$ARGV[0]}
  or die "$ARGV[0] does not exist.\n";


if(@ARGV == 2) {
  exists $file->{net}{$ARGV[0]}{$ARGV[1]}
    or die "NetName $ARGV[0] does not have attribute $ARGV[1].\n";
  print "$file->{net}{$ARGV[0]}{$ARGV[1]}.\n";

} elsif(@ARGV == 1) {
  print "$ARGV[0]:\n";
  print "  $_ = $file->{net}{$ARGV[0]}{$_}\n"
    for keys %{ $file->{net}{$ARGV[0]} };

} else {
  usage();
}

script 1 2 . - 'NetName', , - , . , 'NetName'.

+7

xml_grep2 XML:: LibXML, perl libxml2.

, :

xml_grep2 -t '//net[@NetName="abc"]/@attr3' to_grep.xml

http://xmltwig.com/tool/

+7

xmlgawk XML.

$ xgawk -lxml 'XMLATTR["NetName"]=="abc"{print XMLATTR["attr3"]}' test.xml

XML "345".

+5

xmlgawk XML , awk .

$ nawk -F '[ ="]+' '/abc/{for(i=1;i<=NF;i++){if($i=="attr3"){print $(i+1)}}}' test.xml

script "345". , , awk XML.

+2

Source: https://habr.com/ru/post/1709062/


All Articles