c# – What is better to use for XAML parsing?

Question:

I recently read that it is not recommended to use regular expressions for parsing html, since there is a special library. Well, here's the question: is there something better than regular expressions for parsing XAML? Additional Information:

  1. I write in C#
  2. It is desirable that the tool works with a string, and not with a file.
  3. Purpose: Finding duplicate markup, reducing its volume and rearranging attributes.

Answer:

  • If you need fine-grained syntax control, then use XML parsers: new System.Xml.Linq.XDocument , old System.Xml.XmlDocument .

    XAML is a superset of XML along with all the space and namespaces and all, so any XML parser will be able to handle XAML. Note that in this case, you will get the markup extension as a simple string, and type mapping will have to be done manually if you need it.

  • If you need a deep understanding of the structure (along with the markup extension, mapping to real types, and other XAML overlays on top of basic XML), then use the XAML parser: System.Xaml.XamlServices .

    You'll lose control over the syntax (unless you're only serializing your classes), but you'll have a fully parsed object tree that can be modified and subsequently serialized.

If you need cross-platform, then please note that the XAML parser in Mono does not support all features (read: flawed to the point of impossibility and absolutely useless), and different Windows platforms have their own separate parsers of XAML dialects (read: you can parse only XAML that comes from native platforms). At the same time, the XAML parser does not seem to be planned in CoreCLR either.

Scroll to Top