Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

parse an xml file for a field and create dir

Status
Not open for further replies.

springz33

Technical User
Mar 9, 2004
3
0
0
CA

I'm new in using C#

I have two directories, inbox and outbox. My xml files are stored in the inbox.

Part of my xml file looks like this:

<to:>greg, sally</to:>
<from:>john</from:>
<message>hi</message>

I need to know how to grab the information in the 'to' field of the xml file and create a new directory for each name in the outbox and copying the xml files to the created directories.

Currently I have batch files that will move xml files from the inbox to outbox and create directories for them in the outbox but this is only based on the name of the xml file.

thanks,
 
The XMLTextReader would be your best bet, but your sample isn't valid XML. The :'s in the tags will throw exceptions. If you can get rid of those, then you can use the XML text reader... otherwise you will have to design your own custom parser. Second, you will need an opening and closing node for the xml elements:

Code:
<envelope>
  <to>you</to>
  <from>me</from>
  <message>hi</message>
</envelope>

If you have multiple "envelopes", they too will need a starting and ending node:

Code:
<mailbox>
  <envelope>
    <to>you</to>
    <from>me</from>
    <message>hi</message>
  </envelope>
  <envelope>
    <to>you</to>
    <from>me</from>
    <message>there</message>
  </envelope>
</mailbox>

Next up, you need to use an XmlTextReader (part of the System.Xml namespace) to iterate the nodes.

Code:
// assumes your xml is in a message.xml file
XmlTextReader xml = new XmlTextReader( new StreamReader( "message.xml" ) );
      
while ( xml.Read() )
{
  // look for the start of the envelope
  if ( xml.IsStartElement( "envelope" ) )
  {
    xml.ReadStartElement( "envelope" );

    string to = xml.ReadElementString( "to" );
    string from = xml.ReadElementString( "from" );
    string message = xml.ReadElementString( "message" );

    // do whatever I/O operations here
  }
}

xml.Close();

There are numerous FAQs for performing IO operations (creating directories and such). Parsing XML can be somewhat tricky, though... especially since the only error the XmlTextReader likes to throw is really descriptive: "System Error.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top