Jonathan Lam
Jonathan Lam

Reputation: 185

Reading XML file in C#

a portion of an xml file:

 <publisher>
    <name>ABC</name>
    <id>943</id>
 </publisher>

c#:

string publisher = n.SelectSingleNode(".//publisher").InnerText;
        Console.WriteLine(publisher + "\n");

The c# program reads text off an xml file. The problem I'm having is that the publisher will have a string value of ABC943. Is there a way to just return the string value ABC?

Okay thanks for the answer. I have another question!!! Let's say:

 <publisher>
    <name>ABC</name>
    <id>943</id>
  </publisher>
  <publisher>
    <name>DEF</name>
    <id>3453</id>
  </publisher>

C# code:

string publisher = n.SelectSingleNode(".//publisher//name").InnerText; Console.WriteLine(publisher + "\n");

Now, this will only read ABC. What do I do to make it read ABC, DEF? The number of publishers may vary..

Upvotes: 1

Views: 108

Answers (2)

Chris Walsh
Chris Walsh

Reputation: 3523

Another solution:

publisher = n.SelectSingleNode("//publisher/name/text()");
Console.WriteLine(publisher + "\n");

Also, you don't require the . at the start of the xpath. "//" takes you too the root of the document.

In response to your second question, if you only want the first "name" then use this xpath:

//publisher/name[1]/text()

Upvotes: 0

James Hay
James Hay

Reputation: 7325

publisher = n.SelectSingleNode(".//publisher//name").InnerText;
Console.WriteLine(publisher + "\n");

For multiple nodes use XmlNode.SelectNodes:

XmlNodeList xnl = n.SelectNodes(".//publisher//name");

foreach(XmlNode xn in xnl)
{
    Console.WriteLine(xn.InnerText + "\n");
}

Upvotes: 3

Related Questions