What Xml manipulation component should I use with .Net 4?
It's been lon开发者_JAVA技巧g time I manipulated raw XML. I have used XmlDocument and remember something called XDocument begining to evolve, but that was few years ago. What M$ recomends in these days?
Thanks in advance
XDocument
is part of LINQ to XML - and it's definitely what I'd use for 99% of XML work these days.
LINQ to XML isn't quite what it sounds like - it's not really a LINQ provider in the way that LINQ to SQL is, for example... it's an XML API which has been designed to play well with LINQ to Objects. It supports a declarative construction model and its querying fits in very well with LINQ to Objects, allowing you to find elements, attributes etc really easily.
Oh, and its namespace support is awesomely simple:
XNamespace ns = "http://some.url.here";
XElement element = new XElement(ns + "elementName");
Basically it's lovely - it beats using XmlDocument and XmlReader into a cocked hat, for most situations. Occasionally XmlReader
may be useful for streaming efficiency, but you can create an XElement
from an XmlReader
, which will just read the "current" element and leave the XmlReader
positioned after it. This allows for sort of "structured streaming" with the benefits of LINQ to XML, so long as you only need one element (and any child elements, of course) at a time.
With respect to eidylon's answer: C# doesn't support XML literals; it takes the view that a language shouldn't get involved in a specific technology such as XML directly. How big a deal you believe that to be is a personal matter :)
Which language? In VB.NET the recommended way is with XML literals and the associated props/methods.
For example:
Dim x = XElement.Parse("<some valid xml string>")
Console.WriteLine(x.<someNode>.<someChild>.value)
would write out the value of the someChild node under someNode under the root. I'm not sure if C# has the same construct of being able to directly query nodes/attributes like this or not.
精彩评论