I have a xaml resource dictionary as below
<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:sys="clr-namespace:System;assembly=mscorlib"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:loc="http://temp/uri"
mc:Ignorable="loc">
<sys:String x:Key="ResouceKey" loc:Note="This is a note for the resource.">ResourceText</sys:String>
</ResourceDictionary>
I am looping through all .xaml files in and trying to convert to POCO class and get the loc:Note attributes as well with using XamlReader.
using (var sr = new StreamReader(...))
{
var xamlreader = new XamlReader();
var resourceDictionary = xamlreader.LoadAsync(sr.BaseStream) as ResourceDictionary;
if (resourceDictionary == null)
{
continue;
}
foreach (var key in resourceDictionary.Keys)
{
// In this loop i would like to get the loc:Note
var translation = new Translation
{
LocaleKey = locale,
Note = string.Empty, // How to get the note from the xaml
Text = resourceDictionary[key] as string
});
}
}
Is this possible or do I have to resort to using custom xml serialization logic?
The XamlReader
contains a Dictionary with key/value pair only. It will ignore custom attributes unless you create your own class or type. String is a primitive item and will be shown as such, not a class that may have other properties.
It would be cleaner and safer to just create a class:
public class MyString {
public string _string { get; set; }
public string _note { get; set; }
}
And then store those in your ResourceDictionary. Now you can convert the value as so: (MyString)r.Values[0]
and then assign them to your Translation
object.
Ended up using Xdocument to read the xaml resources.
var xdoc = XDocument.Load(...);
if (xdoc.Root != null)
{
XNamespace xNs = "http://schemas.microsoft.com/winfx/2006/xaml";
XNamespace sysNs = "clr-namespace:System;assembly=mscorlib";
XNamespace locNs = "http://temp/uri";
foreach (var str in xdoc.Root.Elements(sysNs + "String"))
{
var keyAttribute = str.Attribute(xNs + "Key");
if (keyAttribute == null)
{
continue;
}
var noteAttribute = str.Attribute(locNs + "Note");
var translation = new Translation
{
LocaleKey = locale,
Note = noteAttribute != null ? noteAttribute.Value : null,
Text = str.Value
});
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.