Xdocument with Xpath - c#

using XDocument with xpath to parse XML
which one is better in perfomance ?
e.g. To search for tag and get value in xml
tags = xmlDoc.Descendants(xmlTag);
or
xml.SelectSingleNode("//root/node")
So which one will be faster?

XPath doesn't parse XML... it's a query language used on top of any other XML API which supports it. (For example, you can use XPath over XmlDocument or XDocument.)
To find out which query would be faster usefully, you should try your actual XPath and LINQ to XML query on samples of your actual data. I would expect XPath to be faster in some situations, and LINQ to XML to be faster in others.
However, I'd be surprised if the query execution speed was actually the bottleneck in your code - do you have evidence that it is? You should first be asking yourself which is most readable. Implement that code, then see whether it's fast enough.

Related

replacing substring inside attributes of XmlDocument

I'm using C# with .net 3.5 and have a few cases where I want to replace some substrings in the XML attributes of an XmlDocument with something else.
One case is to replace the single quote character with ' and the other is to clean up some files that contain valid XML but the attributes' values are no longer appropriate (say replace anything attribute which starts with "myMachine" with "newMachine").
Is there a simple way to do this, or do I need to go through each attribute of every node (recursively)?
One way to approach it is to select a list of the correct elements using Linq to XML, and then iterate over that list. Here's an example one-liner:
XDocument doc = XDocument.Load(path);
doc.XPathSelectElements("//element[#attribute-name = 'myMachine']").ToList().ForEach(x => x.SetAttributeValue("attribute-name", "newMachine"));
You could also do a more traditional iteration.
I suggest taking a look at LINQ to XML. There's a collection of code snippets that can help you get started here - LINQ To XML Tutorials with Examples
LINQ to XML should allow you to do what you're looking to do, and you'll probably find it easy once you've played with it a bit.

LINQ to XML:Is XNode query possible

I want to use LINQ to XML in Silverlight 3 since there is no XPath support.
I have kind of got the hang of it. But the project I'm working on will not guarantee that all the XML tags I will be querying for will appear in the result XML file.
Due to this I will not be able to query the overall file as XDocument becase the absence of the tag in one document will jumble up the enumeration.
Is there anyway to typecast an XNode to XDocument? I am asking this as I am not able to query the XNode.
Even with LINQ-to-XML you should be querying by name, so I'm not sure why the absence of any particular tag should "jumble up the enumeration" - simply; you might have some nulls, i.e.
var customer = node.Element("Foo");
// now test for null ;p
You can't cast an arbitrary XNode to an XDocument, but if you are sure it is an element, casting to XElement should provide what you need.
Note also that when value nodes may be missing, you might find it easiest to use the conversion operators:
var auditDate = (DateTime?)e.Element("AuditDate");
if <AuditDate> doesn't exist, this will return an empty Nullable<DateTime> - same approach works for most common value-types, or for strings just convert to string.

Put prefix on all elements of xml document

I'm using C# and i need to create a XML document. Ok, i did, but, in each element i need to put a tc prefix.
The only way that i know, is using xmlDoc.CreateElement("tc", "node1", "file.xsd"), but it is very massive because i have lots of tags and my program its already writted.
Is this the only way?
This might work for you:
XmlReader - I need to edit an element and produce a new one
If you're lucky enough to be using C# 3.5, take a look at LINQ to XML.
Here's a document on How to: Create a Document with Namespaces (C#) (LINQ to XML) from MSDN for the LINQ to XML API.
And if you've never seen LINQ to XML before, take a look at this 5 minute overview

Xpathexpression AddSort on multilpe field?

My application will process more than 10000 xml documents as batch. while processing I want to sort the content of xml documents.
I came accross XpathExpression AddSort method, but how to use i to sort on multiple fields ?
or using xslttranform will be appropriate ?? which is better in term of performance ??
Thanks in advance.
Jon Kra
Let me answer in backorder
To choose between XPath and xsltransfor you should understand if xslt is enough to your batch processing. Most of xml operations can be done in xslt, so think about fully migrate.
Concerning to XPathExpression.AddSort. According to msdn: first argument can be XPathExpression, the second should be IComparer.
This exposes your 2 ways.
Let the XPathExpression to merge 2 or more fields to compare
Let the XPathExpression select some "root" of compare and pass it to IComparer, that in order would extract from "root" expected fields to compare.

Compare two XmlNodes in C#

Is there a simple way to compare two XML structures to determine if they have the same structure and data?
I have a function that returns an XmlNode and I am trying to write unit tests for it. I store the correct XML result in a file. Durring the test I load the file into an XmlDocument, locate the proper XmlNode and compare against the result of the function. A straight compare does not work (as expected) and InnerXml does not work either.
I am considering removing all whitespace from InnerXml and comparing that, or writing my own compare to walk the tree, but I don't like either option much.
XNode.DeepEquals. Read the caveats before using it.
If you must use XmlDocument and its supporting types, consider using Microsoft's XmlDiffPatch, which performs customizable diff-operations on XML data structures.
Like CodeToGlory answered, XNode.DeepEquals() might fit your bill, check the remarks section on the MSDN page.
If you are stuck with XmlDocument (instead of XDocument), the answer is: No, there is no simple (existing way) to do it. XmlNode does not override Equals(), or provide an alternative. But it is not impossible to write, and that same Remarks section can be used as a starting point for a tree-walk algorithm.
Do get a clear picture of your requirements first, concerning Attributes, comments, CDATA nodes etc.

Categories