• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 22693
  • Last Modified:

Convert String to XML

If I have a string which contains proper xml format and I want to convert it to an XML file so I can use Xpath to parse it properly.

How do I do this?

this is the code I want to use to go through an xml file

private void ParseXML(string p_string)
{
   // have to convert p_string to to xml
   XPathDocument Doc = new XPathDocument( [Some_XML_FILE] );
   XPathNavigator nav = Doc.CreateNavigator();
  XPathNodeIterator Iterator = nav.Select("//Title/Name");
   while (Iterator.MoveNext())
   {
    Iterator.Current.Name;
   }
}
0
phunchak
Asked:
phunchak
1 Solution
 
stanscott2Commented:
Do something like this.  My simple example takes an existing string, pulls attributes and writes it to a label on the screen.  You should be able to adapt it easily:

private void ParseXML()
{
     string attrs = "";
     string xmlString = "<data><elem fname='Stan'/><elem fname='Dick'/></data>";
     XmlDocument xmlDoc = new XmlDocument();
     xmlDoc.LoadXml(xmlString);
     XmlNode root = xmlDoc.DocumentElement;
     IEnumerator ienum = root.SelectNodes("/data/elem").GetEnumerator();
     XmlNode curName;
     while (ienum.MoveNext())
     {
          curName = (XmlNode)ienum.Current;
          attrs += curName.Attributes["fname"].Value.ToString();
     }
     Label1.Text = attrs;
}

Hope this helps,

Stan Scott
New York City
0
 
Razzie_Commented:
If you want to use the exact code as in your ParseXML() method, just modify it to:

private void ParseXML(string p_string)
{
  XmlDocument xmlDoc = new XmlDocument();
  xmlDoc.LoadXml(p_string);
  XPathNavigator nav = xmlDoc.CreateNavigator();

  XPathNodeIterator Iterator = nav.Select("//Title/Name");
  while (Iterator.MoveNext())
  {
   Iterator.Current.Name;
  }
}


Regards,
Razzie
0

Featured Post

New feature and membership benefit!

New feature! Upgrade and increase expert visibility of your issues with Priority Questions.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now