1

I am developing a framework, where I need to get the value of the attribute from a line(string) given string of attribute in C#. Example:Here is the XML <av:Button Name="btn_1" Width="80" Height="25" x:Uid="btn_1" av:Canvas.Left="168.1" av:Canvas.Top="95.1" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">My Button Content</av:Button>

When input is Name, it should return btn_1. When input is Width, it should return 80.

PS: I have implemented this using some hard-coded positions of words, but it fails sometime. -TIA

1 Answer 1

1

I would use Linq to XML. It's very easy to use

        String MyXml = "<av:Button Name="btn_1" Width="80" Height="25" x:Uid="btn_1" av:Canvas.Left="168.1" av:Canvas.Top="95.1" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">My Button Content</av:Button>";

        XmlNamespaceManager mngr = new XmlNamespaceManager(new NameTable());
        mngr.AddNamespace("av", "http://www.w3.org/2001/XMLSchema-instance");

        XmlParserContext parserContext = new XmlParserContext(null, mngr, null, XmlSpace.None);

        XmlTextReader txtReader = new XmlTextReader(MyXml, XmlNodeType.Element, parserContext);

        var doc = XElement.Load(txtReader);

        var name = doc.Attribute("Name").Value;
        var width = doc.Attribute("Width").Value;
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks James, But I am unable to get x:Uid, Canvas.Left etc. Can you please make it bit generic, I mean handle Namespaces properly.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.