Ravi Naik
Ravi Naik

Reputation: 513

How to parse XAML file?

I have a xml file which contains path of xaml file ( contins image file information ), now i need to parse xml file and get the image present in xaml and show it to in the window form.

Can some boby help me out on this regard pls?

Upvotes: 1

Views: 5066

Answers (3)

Kenan E. K.
Kenan E. K.

Reputation: 14111

In case you have an xml file (or string) like this:

<ImageData>
    <Path>Res\image.xaml</Path>
</ImageData>

...and a xaml dictionary in the file "Res\image.xaml" like this:

<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
                    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
    <Image x:Key="imageKey" Source="img.jpg"/>
</ResourceDictionary>

...you can get the Source path of the Image element like this (using LINQ to XML):

private string GetImagePath(string xmlString)
{
    XElement xmlData = XElement.Parse(xmlString);

    XElement pathElement = xmlData.XPathSelectElement("ImageData/Path");

    if (pathElement == null) return null;

    string xamlPath = pathElement.Value;

    XElement xamlData = XElement.Load(xamlPath);

    XElement imageElement = xamlData.XPathSelectElement("//Image");

    if (imageElement == null) return null;

    XAttribute pathAttribute = imageElement.Attribute("Source");

    return pathAttribute == null ? null : pathAttribute.Value;
}

This is, of course, a rough guideline on how to do it, certainly you would tweak this after some experimenting, to suit your model.

Upvotes: 2

oltman
oltman

Reputation: 1792

You'll need to be a little bit more specific about how the image file information is formatted, but if it's just stored in the XAML as a file path, using .NET's XMLTextReader should do the trick. c-sharpcorner.com has some good code samples that should help you out.

Upvotes: 0

Richard
Richard

Reputation: 109100

XAML is XML, so parse as XML and use any of those approaches to extracting the required data.

Upvotes: 1

Related Questions