BertalanD
BertalanD

Reputation: 33

How to read an node's content from an Xml file to a string in c# 2.0?

I have this Xml file:

<Element>
<Name>Startlap</Name>
<ToolTip>Magyarország legnagyobb internetes portálja</ToolTip>
<Action>OpenWebPage</Action>
<ActionParam1>http://www.startlap.hu</ActionParam1>
<ActionParam2>default</ActionParam2>
<ActionParam3>false</ActionParam3>
<ImageOnDisk>false</ImageOnDisk>
<ImageOnline>http://www.pro-qaly.hu/files/userfiles/logo-startlap.jpg</ImageOnline>

<Name>secondElement</Name>
<ToolTip>Magyarország legnagyobb internetes portálja</ToolTip>
<Action>OpenWebPage</Action>
<ActionParam1>http://www.startlap.hu</ActionParam1>
<ActionParam2>default</ActionParam2>
<ActionParam3>false</ActionParam3>
<ImageOnDisk>false</ImageOnDisk>
<ImageOnline>http://www.pro-qaly.hu/files/userfiles/logo-startlap.jpg</ImageOnline>

How can I save the first and the second name attribute in c# to their own variables?

Upvotes: 1

Views: 61

Answers (2)

Martin Godzina
Martin Godzina

Reputation: 1575

You need two types to solve this problem:

  1. XmlDocument (to get the XML document)
  2. XmlNodeList (a list which will contain our two name attributes)

So lets do it in code:

System.Xml.XmlDocument doc = new System.XmlDocument(); 
//Loading the Xml document
  doc.load("YourXmlFileUrl.xml");

//geting the Name nodes
System.Xml.XmlNodeList nodes = doc.GetElementsByTagName("Name");

//saving both names into String variables:
String Name_01 = nodes[0].InnerXml;
String Name_02 = nodes[1].InnerXml;

Upvotes: 0

Paweł Dyl
Paweł Dyl

Reputation: 9143

You can use XmlDocument class as follows:

XmlDocument doc = new XmlDocument();
doc.LoadXml(yourXml);
XmlNodeList elements = doc.SelectNodes("//Element/Name");
string name1 = elements[0].InnerText;
string name2 = elements[1].InnerText;

Upvotes: 1

Related Questions