#1
  1. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Nov 2011
    Posts
    1
    Rep Power
    0

    Parse multilpl XML tags using regex


    hi all.
    i need to parse a few tags (their value) from am XML.
    this must be done by regex (don't ask me why )

    for example:

    <name>AAA</name>
    <id>1234</id>
    <gender>M</gender>

    i know the pattern needed for each tag using regex

    string name = "(?<=<name>).+?(?=</name>)";
    string id = "(?<=<id>).+?(?=</id>)";
    string gender = "(?<=<gender>).+?(?=</gender>)";

    i just don't know how to init the Regex object to handle all of them.
    i can do:

    private static readonly Regex rgx1 = new Regex(name);
    private static readonly Regex rgx2 = new Regex(id);
    private static readonly Regex rgx3r = new Regex(gender);

    but I'm guessing that's a terrible waste....

    so my question is - how to init a single Regex to handle multiple patterns?
    and once i did it , how to extract the values from it?

    p.s
    I'm programming in c# if anyone need to know....

    10x alot !
  2. #2
  3. No Profile Picture
    Lost in code
    Devshed Supreme Being (6500+ posts)

    Join Date
    Dec 2004
    Posts
    8,316
    Rep Power
    7170
    Code:
    <(name|id|gender)>(.+?)</\1>
    This uses a back reference so that the closing tag matches the opening tag.

    This regular expression will put the name of the tag into group 1 and the value of the tab into group two.

    Comments on this post

    • ManiacDan agrees
    PHP FAQ

    Originally Posted by Spad
    Ah USB, the only rectangular connector where you have to make 3 attempts before you get it the right way around

IMN logo majestic logo threadwatch logo seochat tools logo