how to get value of XML tag attribute in C#?

S

Saurabh

Hi,
my xml is:
<ROOT>
<FILE NAME="filename">CDATA</FILE>
</ROOT>

this xml is argument to a function in C#.
i want to get the filename in a string variable.
how do i do it???
GetElementByTagname("FILE)[0].Attribute retrieves attributelist
how do i get the value of attribute????
 
D

Daniel

like this:

XmlTextReader tr = new XmlTextReader(filename);
while (tr.Read())
{
if (tr.NodeType == XmlNodeType.Element)
{
switch (tr.LocalName)
{

case ("FILENAME"):
_fileName= int.Parse(tr.ReadString());
break;
}
}
}

but your xml would need to look like this:

<ROOT>
<FILENAME>CDATA</FILENAME>
</ROOT>

that would do it.
 
S

Saurabh

Thanks Daniel, i learned a new way to access XML.
The problem is that the xml has to look like:
<ROOT>
<FILE NAME="filename"></FILE>
</ROOT>

beacuse the xml is generated by a recursive function which scans the
file system (DirectoryInfo ans FileInfo class) and generate a xml. The
exact xxml format is:
<ROOT>
<DIRECTORY>
<FILE NAME="filename">CDATA contains filestream</FILE>
<FILE NAME="filename">CDATA contains filestream</FILE>
</DIRECTORY>
<DIRECTORY>
<FILE NAME="filename">CDATA contains filestream</FILE>
<FILE NAME="filename">CDATA contains filestream</FILE>
</DIRECTORY>
</ROOT>

you never know if the filename can be same with different extension.
just to be precautious i have made the file tag with filename as
attribute.
 
G

GVN

Hi Saurabh,

I hope the following code should help you.

XmlDocument _Document = new XmlDocument();
XmlNodeList properties;
_Document.Load (XmlFileName);
XmlNodeList properties = _Document["Design"].ChildNodes;
foreach (XmlNode property in properties)
{
if(property.HasChildNodes)
{
XmlNodeList childNodes = property.ChildNodes;
foreach(XmlNode childNode in childNodes)
{
MessageBox.Show(childNode.Attributes["FILE"].Value); // You can
show file name.
}
}
}

Thanks,
Muralidhar GVN
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top