SitePoint Sponsor

User Tag List

Results 1 to 2 of 2
  1. #1
    SitePoint Addict
    Join Date
    Jun 2008
    Posts
    205
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    XML file to split

    File.xml

    Code:
    <contacts>
      <entry>
        <name>File1</name>
        <street>123 Platypus Lane</street>
        <city>Burgopolis</city>
        <state>FL</state>
        <zip>12345</zip>
      </entry>
    
     <entry>
        <name>File2</name>
        <street>123 Platypus Lane</street>
        <city>Burgopolis</city>
        <state>FL</state>
        <zip>678</zip>
      </entry>
    
     <entry>
        <name>File3</name>
        <street>123 Platypus Lane</street>
        <city>Burgopolis</city>
        <state>FL</state>
        <zip>910</zip>
      </entry>
    </contacts>
    This is one XML file.
    How to break this into 3 files which contains filename as <name> tag.

    Code:
    #!/usr/bin/perl
    use XML::XPath;
    my $file = 'file.xml';
    my $xp = XML::XPath->new(filename=>$file);
    my $nodeset = $xp->find('//name');
    
    my @names;                   # Where we'll put our results
    if (my @nodelist = $nodeset->get_nodelist) {
      @names = map($_->string_value, @nodelist);
      # Now sort and prepare for output
      @names = sort(@names);
      local $" = "\n";
      print "I found these names:\n@names\n";
    }
    File1.xml, File2.xml,File3.xml will be created.

  2. #2
    SitePoint Zealot Bompa's Avatar
    Join Date
    Feb 2008
    Posts
    179
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    I would first parse this into entries

    while($input =~ /<entry>(.*?)<\/entry>/sg) {
    push(@entries, $1);
    }

    I would then iterate @entries parsing for the <name></name> in order
    to get a filename.

    Bompa


Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •