How to find in Name attribute exists in xml string

  • Thread starter Thread starter Andrus
  • Start date Start date
A

Andrus

Hierarchical XML defines AgMenu
Most menu items contain Name attributes as shown below.

How to determine if menu item with given name exists from Silverlight
application ?
E.q

FindName( "DokG", myxmlmenu )

should return True for menu string below.

Andrus.



<?xml version="1.0" encoding="utf-8" ?>
<Menu>
<MenuItem Content="File">
<Items/>
<MenuItem Content="Document">
<Items>
<MenuItem Content="Invoice" Name="DokG" />
<MenuItem Content="Purchase invoice" Name="DokO" />
<MenuItem Content="Invoice payment" Name="UnpaidG" />
<MenuItem IsSeparator="true" />
<MenuItem Content="Payment order" Name="OmdokM" />
<MenuItem Content="Receipt of the bank" Name="OmdokT" />
<MenuItem Content="Cash receipt" Name="OmdokI" />
<MenuItem Content="Cash disbursement" Name="OmdokA" />
<MenuItem IsSeparator="true" />
<MenuItem Content="Cost document" Name="OmdokK" />
<MenuItem Content="Other outgoings" Name="OmdokJ" />
<MenuItem Content="Other receipts" Name="OmdokU" />
<MenuItem Content="Contract" Name="DokE" />
<MenuItem Content="Realization act" Name="DokR" />
<MenuItem Content="Act" Name="OmdokL" />
<MenuItem IsSeparator="true" />
<MenuItem Content="Pricing" Name="Hkpais" />
<MenuItem Content="Price list" Name="Hkrid" />
<MenuItem Content="Price matrix" Name="Hinnamtr" />
</Items>
</MenuItem>
<MenuItem Content="Warehouse">
<Items>
<MenuItem Content="Dispatch" Name="DokVL" />
<MenuItem Content="Receipt" Name="DokSL" />
<MenuItem Content="Chargeable" Name="DokKL" />
<MenuItem Content="Internal sales" Name="DokIL" />
</Menu>
 
Andrus said:
Hierarchical XML defines AgMenu
Most menu items contain Name attributes as shown below.

How to determine if menu item with given name exists from Silverlight
application ?
E.q

FindName( "DokG", myxmlmenu )

should return True for menu string below.

Use LINQ to XML:

bool FindMenu(string name, string xml)
{
XElement menu = XElement.Parse(xml);
return menu.Descendants("MenuItem").Any(m =>
(string)m.Attribute("Name") == name);
}
 
Andrus said:
Hierarchical XML defines AgMenu
Most menu items contain Name attributes as shown below.

How to determine if menu item with given name exists from Silverlight
application ?
E.q

FindName( "DokG", myxmlmenu )
should return True for menu string below [...]

You can load the XML into an XmlDocument and then use an XPATH query to
search for the name:

using System.Xml;
....
bool FindName(string name, string xml)
{
XmlDocument xd = new XmlDocument();
xd.LoadXml(xml);
return null!=xd.SelectSingleNode("//MenuItem[@Name=\""+name+"\"]");
}
 
Back
Top