2

I'm trying to read the property of a particular element in XAML file, For that I'm using StreamReader(from System.IO). To get the root element I'm using instance of XmlDocument(from System.Xml). After, getting the root element I used XmlNodeList to get collection of nodes.

Here is the code-snippet:

private string Read(string path)
       {
           var reader = new StreamReader(path);
           var content = new StringBuilder("");
           var line = string.Empty;
           while ((line = reader.ReadLine()) != null) content.Append(line);
           reader.Close();
           return TrimBraces(content.ToString());
       }

private void RecursivelyAddChildNodeName(XmlNodeList childNodeValue)
       {
           foreach (var item in childNodeValue)
           {
               if (((XmlElement) item).Name == "Button")
                   ((XmlElement)item).Attributes["Name"].Value.ToString();
               else if (((XmlElement) item).Name == "Label") AddNameToList(item, "Label");

               if (((XmlNode) item).HasChildNodes) RecursivelyAddChildNodeName(((XmlNode) item).ChildNodes);
           }
       }

Is there a way where all the nodes can be fetched and then traverse through it to find the Objects(like Button, TextBox, CheckBox) and get their attributes(like name, id etc.)?

Meenakshi Rana
  • 505
  • 5
  • 8
  • 1
    Why not parsing the logical tree at run-time instead of reading XAMl files as text? – Corentin Pane Oct 12 '19 at 15:50
  • 1
    What you really want to achieve with XAML file parsing? You can load the XAML to and assign to UIElement using `XamlReader.Load` and through which you can traverse the whole logical tree at run time (as suggested by @CorentinPane too). – user1672994 Oct 12 '19 at 16:39
  • 1
    I have XAML file with file name MainWindow.xaml which consists of a Button and CheckBox.`XamlReader.Load(System.IO.Stream stream)` Reads the XAML input in the specified Stream and `XamlReader.Parser(string xmlText)`. for Parsing i used the output of StreamReader as an input for Parser. `var content = Read(localPath); XamlReader.Parse(content);` but getting the exception as "The invocation of constructor on type `System.Windows.Winow`"that matches the specific binding contraints threw an exception Line number 1 and Line position 9 – Meenakshi Rana Oct 12 '19 at 17:19
  • As others have asked, I'm curious: why you are trying to parse the xaml file in the first place? – Keith Stein Oct 13 '19 at 00:53
  • 1
    XAML is just XML with XML-friendly markup embedded in some attribute values. So you "fetch and traverse" nodes in XAML exactly like you would in XML. See marked duplicate. – Peter Duniho Oct 13 '19 at 00:55
  • Is there a way to accomplish this problem using XAML Reader or using Logical Tree? – Meenakshi Rana Oct 13 '19 at 02:43

0 Answers0