将TreeViewItem转换为XElement?

时间:2017-07-07 07:12:00

标签: c# xml wpf linq xsd

我正在尝试遍历两个集合的XElement,以便我可以比较它们,但是我收到了错误:

  

System.InvalidCastException:'无法转换类型的对象   键入'System.Windows.Controls.TreeViewItem'   'System.Xml.Linq.XElement''。

我的代码是:

private void CompareTrees(ItemCollection xml,ItemCollection xsd )
    {               
        bool isMatch = false;
        string header = string.Empty;           

        foreach (XElement xexsd in xsd)
        {
            foreach (XElement xexml in xml)
            {                    
                    if (xexsd.Name.LocalName + " - " + xexsd.Value == xexml.Name.LocalName + " - " + xexsd.Value)
                    {
                    CompareTrees(xml, xsd);
                    isMatch = true;
                    break;
                    }    
            }
            if (isMatch == true)
            {
                continue;
            }
            else
            {
                var item = new ListBoxItem();
                lbItems.Items.Add(item);
            }
        }            
    }

1 个答案:

答案 0 :(得分:1)

显然ItemCollection包含TreeViewItems。试试这个:

foreach (TreeViewItem tvi in xml.OfType<TreeViewItem>())
{
    XElement xexsd = tvi.DataContext as XElement;
    if (xexsd != null && xexsd.Name.LocalName + " - " + xexsd.Value == xexml.Name.LocalName + " - " + xexsd.Value)
    {
        CompareTrees(xml, xsd);
        isMatch = true;
        break;
    }
}