The Woo
The Woo

Reputation: 18645

C# Xml Node to String

I have a XML document with my data in it, multiple entries for the same node fields (StudentID = FirstName, LastName, etc). How do I convert the nodes into string values for each StudentID section?

Upvotes: 0

Views: 19709

Answers (3)

Mikael Svenson
Mikael Svenson

Reputation: 39695

You don't say much about what the xml looks like. But it could go something like this:

string xml = "<nodes><studentid><firstname>Name</firstname><lastname>last</lastname></studentid></nodes>";
XmlDocument doc = new XmlDocument();
doc.LoadXml(xml);
foreach (XmlNode node in doc.SelectNodes("//studentid"))
{ 
   string first = node["firstname"].InnerText;
   string last = node["lastname"].InnerText;
}

If the data is in attributes use something along the lines of:

string first = node.Attributes["firstname"].Value;

You could also look into linq for xml if you have a schema.

Upvotes: 5

o.k.w
o.k.w

Reputation: 25810

Copy and edited from http://www.csharp-examples.net/xml-nodes-by-name/

//on button click before the following:

XmlDocument xml = new XmlDocument();
xml.LoadXml(myXmlString); // suppose that myXmlString contains "<Names>...</Names>"

XmlNodeList xnList = xml.SelectNodes("/Names/Name");
StringBuilder sb = new StringBuilder();
string entry = "Name: {0} {1}\r\n";
foreach (XmlNode xn in xnList)
{
  string firstName = xn["FirstName"].InnerText;
  string lastName = xn["LastName"].InnerText;
  sb.AppendFormat(entry,  firstName, lastName);
}

MessageBox.Show(sb.ToString());

Upvotes: 0

inked
inked

Reputation: 624

Are you looking for the innerText of the node (the value inside the tags, but not the tag attribute data) or the outerXml (which has all the tag data)?

Also, are you using CDATAs? There's a little more you need to do to get data out of those properly.

Or, do you want it all at once -- in which case you'd use an XSLT transformation.

Upvotes: 0

Related Questions