I'm working on a WCF service application which does lot of manipulations on XML files. Before i start looping the nodes, elements, attributes and all the other stuffs i want to know the use开发者_开发问答ful functions that are available on XmlNode, XmlElement, XmlDocument and all other Xml related classes which can be used 'in place of' looping.
For example you can convert List to array using the CopyTo(string[])
.
Thank you.
NLV
Probably the immediate answer is LINQ. A "scratch-pad" example of using it would be:
using System;
using System.Linq;
using System.Xml.Linq;
using System.Xml;
namespace LinqSample1
{
class Program
{
static void Main(string[] args)
{
var xml = @"
<items>
<item>
<name>Item 1</name>
<price>1.00</price>
<quantity>3</quantity>
</item>
<item>
<name>Item 2</name>
<price>1.50</price>
<quantity>1</quantity>
</item>
</items>";
var document = new XmlDocument();
document.LoadXml(xml);
var items = from XmlNode item in document.SelectNodes("/items/item")
select new
{
Name = item.SelectSingleNode("name").InnerText,
Price = item.SelectSingleNode("price").InnerText,
Quantity = item.SelectSingleNode("quantity").InnerText
};
foreach (var item in items)
{
Console.WriteLine("Item Name: {0} costs {1} and we have a quantity of {2}", item.Name, item.Price, item.Quantity);
}
}
}
}
Performance
On the question of performance: only you can answer that, as it's very much dependent on what you're doing and how quickly you need it to do it. If you have a batch process that runs once a month and takes 30 minutes to run, you may well decide that's quick enough. If the code's clear, concise and maintainable then re-writing it so that ran in half the time but was much more convoluted wouldn't be doing you, or anyone else who has to maintain it in the future, any favours.
精彩评论