take data from xml c# - c#

its my xml file:
<?xml version="1.0" encoding="UTF-8"?>
<metadata xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:dc="http://purl.org/dc/elements/1.1/">
<dc:title>Tytu�1</dc:title>
<dc:creator>autor1</dc:creator>
<dc:subject>Tem1</dc:subject>
<dc:description>O1</dc:description>
<dc:publisher>wydawca1</dc:publisher>
<dc:contributor>wsp�tw�rca1</dc:contributor>
<dc:date>data wydania1</dc:date>
<dc:type>typ zasobu1</dc:type>
<dc:format>format1</dc:format>
<dc:identifier>identyfikator1</dc:identifier>
<dc:source>�r�d�o1</dc:source>
<dc:language>j�zyk1</dc:language>
<dc:relation>powi�zania1</dc:relation>
<dc:coverage>zakres1</dc:coverage>
<dc:rights>prawa1</dc:rights>
</metadata>
Here is my code:
using System;
using System.Xml.Linq;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
var dc = "dc";
XDocument doc = XDocument.Load("C:\\Users\\Mateusz\\Desktop\\DublinCore.xml");
var authors = doc.Descendants( dc + "subject");
foreach (var author in authors)
{
Console.WriteLine(author.Value);
}
Console.ReadLine();
}
}
}
I want view in console information about subject.
I think problem is in using namespace.
For example:
<Author>Author</Author> code will work
<dc:Author>Author</Author> code doesn't work
Can someone help me with it?

You need to use XNamespace. So your code becomes:
static void Main(string[] args)
{
XNamespace dc = "http://purl.org/dc/elements/1.1/";
XDocument doc = XDocument.Load("C:\\Users\\Mateusz\\Desktop\\DublinCore.xml");
var authors = doc.Descendants(dc + "subject");
foreach (var author in authors)
{
Console.WriteLine(author.Value);
}
Console.ReadLine();
}
Incidentally it is rather confusing when you use a variable name authors to extract the subject nodes!

Related

XML C# Parse - Complex

I have been on google for a while but am just stumped. I need to parse xml of this nature. I can't seem to skip to elements in the middle, e.g. Folder. I have limited the xml as there were many 'Folder' elements. Any guidance would be appreciated. I was after the FolderID element's attribute ID.
<s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/">
<s:Header>
<h:ServerVersionInfo MajorVersion="14"
MinorVersion="1"
MajorBuildNumber="225"
MinorBuildNumber="46"
Version="Exchange2010_SP1"
xmlns:h="http://schemas.microsoft.com/exchange/services/2006/types"
xmlns="http://schemas.microsoft.com/exchange/services/2006/types"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:xsd="http://www.w3.org/2001/XMLSchema" />
</s:Header>
<s:Body xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<m:GetFolderResponse xmlns:m="http://schemas.microsoft.com/exchange/services/2006/messages"
xmlns:t="http://schemas.microsoft.com/exchange/services/2006/types">
<m:ResponseMessages>
<m:GetFolderResponseMessage ResponseClass="Success">
<m:ResponseCode>NoError</m:ResponseCode>
<m:Folders>
<t:Folder>
<t:FolderId Id="AAMkADk5MmY1ZThmLTM2MzAtNGVh" ChangeKey="AQAAABYAAACSe/NBrSZiQKqHx8yL+lIRAAAA1EWM" />
<t:ParentFolderId Id="AAMkADk5MmY1ZThmLTM2MzAtNGVh" ChangeKey="AQAAAA==" />
<t:DisplayName>Top of Information Store</t:DisplayName>
<t:TotalCount>0</t:TotalCount>
<t:ChildFolderCount>15</t:ChildFolderCount>
<t:EffectiveRights>
<t:CreateAssociated>true</t:CreateAssociated>
<t:CreateContents>true</t:CreateContents>
<t:CreateHierarchy>true</t:CreateHierarchy>
<t:Delete>true</t:Delete>
<t:Modify>true</t:Modify>
<t:Read>true</t:Read>
<t:ViewPrivateItems>true</t:ViewPrivateItems>
</t:EffectiveRights>
<t:PermissionSet>
<t:Permissions>
<t:Permission>
<t:UserId>
<t:DistinguishedUser>Default</t:DistinguishedUser>
</t:UserId>
<t:CanCreateItems>false</t:CanCreateItems>
<t:CanCreateSubFolders>false</t:CanCreateSubFolders>
<t:IsFolderOwner>false</t:IsFolderOwner>
<t:IsFolderVisible>false</t:IsFolderVisible>
<t:IsFolderContact>false</t:IsFolderContact>
<t:EditItems>None</t:EditItems>
<t:DeleteItems>None</t:DeleteItems>
<t:ReadItems>None</t:ReadItems>
<t:PermissionLevel>None</t:PermissionLevel>
</t:Permission>
<t:Permission>
<t:UserId>
<t:DistinguishedUser>Anonymous</t:DistinguishedUser>
</t:UserId>
<t:CanCreateItems>false</t:CanCreateItems>
<t:CanCreateSubFolders>false</t:CanCreateSubFolders>
<t:IsFolderOwner>false</t:IsFolderOwner>
<t:IsFolderVisible>false</t:IsFolderVisible>
<t:IsFolderContact>false</t:IsFolderContact>
<t:EditItems>None</t:EditItems>
<t:DeleteItems>None</t:DeleteItems>
<t:ReadItems>None</t:ReadItems>
<t:PermissionLevel>None</t:PermissionLevel>
</t:Permission>
</t:Permissions>
</t:PermissionSet>
<t:UnreadCount>0</t:UnreadCount>
</t:Folder>
</m:Folders>
</m:GetFolderResponseMessage>
</m:ResponseMessages>
</m:GetFolderResponse>
</s:Body>
</s:Envelope>
LINQ to XML is the best .NET XML Parsing API.
See
https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/concepts/linq/xdocument-class-overview
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Linq;
namespace ConsoleApp12
{
class Program
{
static void Main(string[] args)
{
var doc = XDocument.Load(#"c:\temp\foo.xml");
var ns = (XNamespace)"http://schemas.microsoft.com/exchange/services/2006/types";
var folders = doc.Descendants(ns + "Folder");
foreach (var e in folders)
{
var folderId = e.Element(ns + "FolderId").Attribute("Id").Value;
Console.WriteLine(folderId);
}
Console.WriteLine("Hit any key to exit.");
Console.ReadKey();
}
}
}
You should learn about serlialization. It's very easy to convert an XML to and from a object in C#. https://www.codeproject.com/Articles/483055/XML-Serialization-and-Deserialization-Part
That said, this will get you the data you're after. It's not very reusable and won't help you with any xml files other than ones with one instance of that attribute, but it's what you're after so here you go.
string FolderId;
string ChangeKey;
using (StreamReader sr = new StreamReader("c:\\myfile.xml"))
{
string line;
while ((line = sr.ReadLine()) != null)
{
if (line.Contains("<t:FolderId Id="))
{
try
{
var lineArray = line.Split('\"');
FolderId = lineArray[1];
ChangeKey = lineArray[3];
}
catch
{
// handle exception
}
}
}
}
You can use the XSD.exe to create a schema class. and then using XML deserializer, you can deserialize/parse xml to object
Using xml linq
XDocument doc = XDocument.Load(FILENAME);
List<XElement> folders = doc.Descendants().Where(x => x.Name.LocalName == "Folder").ToList();
XNamespace tNs = folders.FirstOrDefault().GetNamespaceOfPrefix("t");
XElement id_AAMkADk5MmY1ZThmLTM2MzAtNGVh = folders.Where(x => (string)x.Element(tNs + "FolderId").Attribute("Id") == "AAMkADk5MmY1ZThmLTM2MzAtNGVh").FirstOrDefault();

Parse the Nodes of XML files

How to parse all the XML files under a given directory as an input to the application and write its output to a text file.
Note: The XML is not always the same the nodes in the XML can vary and have any number of Child-nodes.
Any help or guidance would be really helpful on this regard :)
XML File Sample
<CATALOG>
<CD>
<TITLE>Empire Burlesque</TITLE>
<ARTIST>Bob Dylan</ARTIST>
<COUNTRY>
<CNT>USA</CNT>
<CODE>3456</CODE>
</COUNTRY>
<COMPANY>Columbia</COMPANY>
<PRICE>10.90</PRICE>
<YEAR>1985</YEAR>
</CD>
<CD>
<TITLE>Hide your heart</TITLE>
<ARTIST>Bonnie Tyler</ARTIST>
<COUNTRY>UK</COUNTRY>
<COMPANY>CBS Records</COMPANY>
<PRICE>9.90</PRICE>
<YEAR>1988</YEAR>
</CD>
</CATALOG>
C# Code
using System;
using System.Collections.Generic;
using System.Windows.Forms;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
using System.Data;
using System.Xml;
using System.Xml.Linq;
namespace XMLTagParser
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Please Enter the Location of the file");
// get the location we want to get the sitemaps from
string dirLoc = Console.ReadLine();
// get all the sitemaps
string[] sitemaps = Directory.GetFiles(dirLoc);
StreamWriter sw = new StreamWriter(Application.StartupPath + #"\locs.txt", true);
// loop through each file
foreach (string sitemap in sitemaps)
{
try
{
// new xdoc instance
XmlDocument xDoc = new XmlDocument();
//load up the xml from the location
xDoc.Load(sitemap);
// cycle through each child noed
foreach (XmlNode node in xDoc.DocumentElement.ChildNodes)
{
// first node is the url ... have to go to nexted loc node
foreach (XmlNode locNode in node)
{
string loc = locNode.Name;
// write it to the console so you can see its working
Console.WriteLine(loc + Environment.NewLine);
// write it to the file
sw.Write(loc + Environment.NewLine);
}
}
}
catch {
Console.WriteLine("Error :-(");
}
}
Console.WriteLine("All Done :-)");
Console.ReadLine();
}
}
}
Preferred Output:
CATALOG/CD/TITLE
CATALOG/CD/ARTIST
CATALOG/CD/COUNTRY/CNT
CATALOG/CD/COUNTRY/CODE
CATALOG/CD/COMPANY
CATALOG/CD/PRICE
CATALOG/CD/YEAR
CATALOG/CD/TITLE
CATALOG/CD/ARTIST
CATALOG/CD/COUNTRY
CATALOG/CD/COMPANY
CATALOG/CD/PRICE
CATALOG/CD/YEAR
This is a recursive problem, and what you are looking for is called 'tree traversal'. What this means is that for each child node, you want to look into it's children, then into that node's children (if it has any) and so on, recording the 'path' as you go along, but only printing out the names of the 'leaf' nodes.
You will need a function like this to 'traverse' the tree:
static void traverse(XmlNodeList nodes, string parentPath)
{
foreach (XmlNode node in nodes)
{
string thisPath = parentPath;
if (node.NodeType != XmlNodeType.Text)
{
//Prevent adding "#text" at the end of every chain
thisPath += "/" + node.Name;
}
if (!node.HasChildNodes)
{
//Only print out this path if it is at the end of a chain
Console.WriteLine(thisPath);
}
//Look into the child nodes using this function recursively
traverse(node.ChildNodes, thisPath);
}
}
And then here is how I would add it into your program (within your foreach sitemap loop):
try
{
// new xdoc instance
XmlDocument xDoc = new XmlDocument();
//load up the xml from the location
xDoc.Load(sitemap);
// start traversing from the children of the root node
var rootNode = xDoc.FirstChild;
traverse(rootNode.ChildNodes, rootNode.Name);
}
catch
{
Console.WriteLine("Error :-(");
}
I made use of this other helpful answer: Traverse a XML using Recursive function
Hope this helps! :)

Handling C# XML Deserialization with Namespaces

I have been wrestling with deserializing the following XML document:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<w:settings xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:o="urn:schemas-microsoft-com:office:office" xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships" xmlns:m="http://schemas.openxmlformats.org/officeDocument/2006/math" xmlns:v="urn:schemas-microsoft-com:vml" xmlns:w10="urn:schemas-microsoft-com:office:word" xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main" xmlns:w14="http://schemas.microsoft.com/office/word/2010/wordml" xmlns:w15="http://schemas.microsoft.com/office/word/2012/wordml" xmlns:sl="http://schemas.openxmlformats.org/schemaLibrary/2006/main" mc:Ignorable="w14 w15">
<w:zoom w:percent="100"></w:zoom>
<w:proofState w:spelling="clean" w:grammar="clean"></w:proofState>
<w:defaultTabStop w:val="720"></w:defaultTabStop>
<w:characterSpacingControl w:val="doNotCompress"></w:characterSpacingControl>
<w:compat>
<w:compatSetting w:name="compatibilityMode" w:uri="http://schemas.microsoft.com/office/word" w:val="15"></w:compatSetting>
<w:compatSetting w:name="overrideTableStyleFontSizeAndJustification" w:uri="http://schemas.microsoft.com/office/word" w:val="1"></w:compatSetting>
<w:compatSetting w:name="enableOpenTypeFeatures" w:uri="http://schemas.microsoft.com/office/word" w:val="1"></w:compatSetting>
<w:compatSetting w:name="doNotFlipMirrorIndents" w:uri="http://schemas.microsoft.com/office/word" w:val="1"></w:compatSetting>
<w:compatSetting w:name="differentiateMultirowTableHeaders" w:uri="http://schemas.microsoft.com/office/word" w:val="1"></w:compatSetting>
</w:compat>
<w:rsids>
<w:rsidRoot w:val="00B31FC7"></w:rsidRoot>
<w:rsid w:val="00251096"></w:rsid>
<w:rsid w:val="00481AA7"></w:rsid>
<w:rsid w:val="005C6856"></w:rsid>
<w:rsid w:val="00661DE2"></w:rsid>
<w:rsid w:val="00984D97"></w:rsid>
<w:rsid w:val="00A06ADC"></w:rsid>
<w:rsid w:val="00B31FC7"></w:rsid>
</w:rsids>
<m:mathPr>
<m:mathFont m:val="Cambria Math"></m:mathFont>
<m:brkBin m:val="before"></m:brkBin>
<m:brkBinSub m:val="--"></m:brkBinSub>
<m:smallFrac m:val="0"></m:smallFrac>
<m:dispDef></m:dispDef>
<m:lMargin m:val="0"></m:lMargin>
<m:rMargin m:val="0"></m:rMargin>
<m:defJc m:val="centerGroup"></m:defJc>
<m:wrapIndent m:val="1440"></m:wrapIndent>
<m:intLim m:val="subSup"></m:intLim>
<m:naryLim m:val="undOvr"></m:naryLim>
</m:mathPr>
<w:themeFontLang w:val="en-US"></w:themeFontLang>
<w:clrSchemeMapping w:bg1="light1" w:t1="dark1" w:bg2="light2" w:t2="dark2" w:accent1="accent1" w:accent2="accent2" w:accent3="accent3" w:accent4="accent4" w:accent5="accent5" w:accent6="accent6" w:hyperlink="hyperlink" w:followedHyperlink="followedHyperlink"></w:clrSchemeMapping>
<w:shapeDefaults>
<o:shapedefaults v:ext="edit" spidmax="1026"></o:shapedefaults>
<o:shapelayout v:ext="edit">
<o:idmap v:ext="edit" data="1"></o:idmap>
</o:shapelayout>
</w:shapeDefaults>
<w:decimalSymbol w:val="."></w:decimalSymbol>
<w:listSeparator w:val=","></w:listSeparator>
<w15:chartTrackingRefBased></w15:chartTrackingRefBased>
<w15:docId w15:val="{23720E07-DD19-46BC-8098-ED32713AB32B}"></w15:docId>
</w:settings>
I am only interested in what is contained within the rsids element. So I thought I could create classes that looked like this:
[XmlRoot(ElementName ="settings", Namespace = "http://schemas.openxmlformats.org/wordprocessingml/2006/main")]
public class rsids
{
[XmlElement(ElementName ="rsids",Namespace = "http://schemas.openxmlformats.org/wordprocessingml/2006/main")]
public List<rsid> Rsids { get; set; }
}
public class rsid
{
[XmlAttribute(Namespace = "http://schemas.openxmlformats.org/wordprocessingml/2006/main")]
public static string val { get; set; }
}
I am attempting to deserialize like this:
XDocument xdoc = XDocument.Load(file);
using (TextReader reader = new StringReader(xdoc.ToString()))
{
try
{
XmlSerializer xmlSerializer = new XmlSerializer(typeof(rsids));
StreamReader sr = new StreamReader(file);
rsids SettingsXml = (rsids)xmlSerializer.Deserialize(sr);
foreach (var rsid in SettingsXml.Rsids)
{
Console.WriteLine(rsid.val.Count());
}
Console.ReadLine();
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
Console.ReadLine();
}
}
However, I am getting the following error: "Value cannot be null". This is my first attempt at deserializing an XML document with Namespaces. I have browsed the community and found plenty of articles of folks having similar issues however, after trying some of those solutions I am just as confused as when I started and just going in circles. I want to understand this. Some of those posted solutions out there seem to indicate I only have to add a blank Namespace attribute to my decorators (Namespace ="") and others show the actual namespace uri being referenced but only for the root element leaving blanks in subsequent elements \ attributes. I am more looking for the education as to 'why'\'when' to use one method over another and an example of how to accomplish this given the XML below. I appreciate any help you can provide.
Cheers
You're not too far off.
Your XmlElement attribute implies multiple rsids elements. What you want is a single rsids element containing multiple rsid elements. The easiest way to do this is using the XmlArray and XmlArrayItem attributes.
The val property shouldn't be static
Due to what looks like a bug in XmlSerializer, you need to include Form = XmlSchemaForm.Qualified in your XmlAttribute attribute.
You can also omit most of your Namespace properties as they'll be inherited, and ElementName doesn't have to be specified explicitly.
Putting all that together:
[XmlRoot(Namespace = "http://schemas.openxmlformats.org/wordprocessingml/2006/main")]
public class settings
{
[XmlArray("rsids")]
[XmlArrayItem("rsid")]
public List<rsid> Rsids { get; set; }
}
public class rsid
{
[XmlAttribute(Form = XmlSchemaForm.Qualified)]
public string val { get; set; }
}
Of course, if that's all you want then a simple LINQ to XML query would be a lot easier:
XNamespace w = "http://schemas.openxmlformats.org/wordprocessingml/2006/main";
var rsids = doc.Descendants(w + "rsid")
.Attributes(w + "val")
.Select(x => x.Value);
See this fiddle for a working demo of both approaches.
Try this
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Linq;
namespace ConsoleApplication1
{
class Program
{
const string FILENAME = #"c:\temp\test.xml";
static void Main(string[] args)
{
XDocument doc = XDocument.Load(FILENAME);
int[] rsids = doc.Descendants().Where(x => x.Name.LocalName == "rsids").Select(x => new {
rsids = x.Elements().Select(y => int.Parse((string)y.Attribute(x.GetNamespaceOfPrefix("w") + "val"), System.Globalization.NumberStyles.HexNumber))
}).Select(x => x.rsids).FirstOrDefault().Select(x => x).ToArray();
}
}
}

How To Check if an Object is Instantiated?

I'm trying to list down all elements and attributes of an xml into two separate List objects.
I was able to get all the elements in the xml.
But when I tried to add the functionality to get all the attributes within each element, I always encounter System.NullReferenceException: Object reference not set to an instance of an object.
Please review my code below and advise where I'm not doing it right. Or is there any better way to accomplish this? Your comments and suggestions will be highly appreciated.
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Windows.Forms;
using System.Xml;
using System.IO;
namespace TestGetElementsAndAttributes
{
public partial class MainForm : Form
{
List<string> _elementsCollection = new List<string>();
List<string> _attributeCollection = new List<string>();
public MainForm()
{
InitializeComponent();
XmlDataDocument xmldoc = new XmlDataDocument();
FileStream fs = new FileStream(#"C:\Test.xml", FileMode.Open, FileAccess.Read);
xmldoc.Load(fs);
XmlNode xmlnode = xmldoc.ChildNodes[1];
AddNode(xmlnode);
}
private void AddNode(XmlNode inXmlNode)
{
try
{
if(inXmlNode.HasChildNodes)
{
foreach (XmlNode childNode in inXmlNode.ChildNodes)
{
foreach(XmlAttribute attrib in childNode.Attributes)
{
_attributeCollection.Add(attrib.Name);
}
AddNode(childNode);
}
}
else
{
_elementsCollection.Add(inXmlNode.ParentNode.Name);
}
}
catch(Exception ex)
{
MessageBox.Show(ex.GetBaseException().ToString());
}
}
}
}
Posting as well the sample XML.
<?xml version="1.0" encoding="UTF-8" ?>
<DocumentName1>
<Product>
<Material_Number>21004903</Material_Number>
<Description lang="EN">LYNX GIFT MUSIC 2012 1X3 UNITS</Description>
<Packaging_Material type="25">457</Packaging_Material>
</Product>
</DocumentName1>
You should check the existence of childNode.Attributes with something like this:
if (childNode.Attributes != null)
{
foreach(XmlAttribute attrib in childNode.Attributes)
{
...
}
}
You need to make sure childNode.Attributes has values, so add if statement prior
if (childNode.Attributes != null)
{
foreach(XmlAttribute attrib in childNode.Attributes)

XmlAttributeCollection isn't able to get attributes from xml

I'm using System.Xml to get attributes from my xml file.
It seems that following code which I found somewhere is able to find nodes correctly however it doesn't recognizes attributes (it's weird because I've created this xml files with System.Xml too):
DataSet task_data = new DataSet("Root");
adapter.Fill(task_data); // MySqlDataAdapter is being used here
task_data.WriteXml(path, XmlWriteMode.WriteSchema);
So I don't know why any other xml which can be found on the internet works and mine which was created with the same module doesn't...
using System;
using System.Xml;
using System.IO;
public class Catalog
{
private XmlDocument xmldoc;
private string path = #"C:\Users\Me\Desktop\task.xml";
public static void Main()
{
Catalog c = new Catalog();
}
public Catalog()
//Constructor
{
FileStream fs = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
xmldoc = new XmlDocument();
xmldoc.Load(fs);
DisplayCatalog();
}
// Method for Displaying the catalog
private void DisplayCatalog()
{
XmlNodeList xmlnode = xmldoc.GetElementsByTagName("task");
Console.WriteLine("Here is the list of catalogs\n\n");
for (int i = 0; i < xmlnode.Count; i++)
{
XmlAttributeCollection xmlattrc = xmlnode[i].Attributes; //HERE IS THE PROBLEM!!!
Console.Write(xmlnode[i].FirstChild.Name);
Console.WriteLine(":\t\t" + xmlnode[i].FirstChild.InnerText);
Console.Write(xmlnode[i].LastChild.Name);
Console.WriteLine(":\t" + xmlnode[i].LastChild.InnerText);
Console.WriteLine();
}
Console.WriteLine("Catalog Finished");
}
//end of class
}
This is the xml you linked to contins no attributes only nodes.
<?xml version="1.0" standalone="yes"?>
<Root>
<task>
<TaskId>1</TaskId>
<TaskDelegatorNote>Presentation</TaskDelegatorNote>
<StartTime>PT10H</StartTime>
<EndTime>PT13H</EndTime>
<TaskEndDate>2011-01-02T00:00:00+00:00</TaskEndDate>
<TaskContractorNote>Done</TaskContractorNote>
<TaskStatus>3</TaskStatus>
<LastModification>Me, 2003-05-15 13:48:59</LastModification>
</task>
<task>
<TaskId>2</TaskId>
<TaskDelegatorNote>It must be done.</TaskDelegatorNote>
<StartTime>PT10H</StartTime>
<EndTime>PT13H</EndTime>
<TaskEndDate>2011-01-02T00:00:00+00:00</TaskEndDate>
<TaskContractorNote />
<TaskStatus>2</TaskStatus>
<LastModification>Admin, 2009-08-04 10:30:49</LastModification>
</task>
</Root>
Here's an xml snippint with a TaskId attribute
<task TaskId = 1>
</task>
To fix this change
Console.Write(xmlattrc[0].Name);
Console.WriteLine(":\t\t" + xmlattrc[0].Value);
to
Console.Write(xmlnode[0].ChildNodes[0].Name);
Console.WriteLine(":\t\t" + xmlnode[0].ChildNodes[0].Value);
Your output would be
Here is the list of catalogs
TaskId:
TaskId: 1
LastModification: Me, 2003-05-15 13:48:59
TaskId:
TaskId: 2
LastModification: Admin, 2009-08-04 10:30:49
Catalog Finished
Press any key to continue . . .
Also you should look at LinqToXML for some other ways of doing projections of your xml nodes

Categories