2012-12-30 79 views
0

我正在使用visual studio for windows phone,并且当XML数据的父级中存在属性时,我的XML读取器代码不工作。XML读取器在使用xmlns属性时找不到元素

我的C#代码

namespace youtube_xml 
{ 
    public partial class MainPage : PhoneApplicationPage 
    { 
    // Constructor 
    public MainPage() 
    { 
     InitializeComponent(); 
     SupportedOrientations = SupportedPageOrientation.PortraitOrLandscape; 
    } 
    private void listBox1_Loaded(object sender, RoutedEventArgs e) 
    { 
     var element = XElement.Load("Authors.xml"); 
     var authors = 
     from var in element.Descendants("feed") 
     select new Authors 
     { 
      AuthorName = var.Attribute("scheme").Value, 
     }; 

     listBoxAuthors.DataContext = authors; 
    } 
    public ImageSource GetImage(string path) 
    { 
     return new BitmapImage(new Uri(path, UriKind.Relative)); 
    } 
    } 
} 

工作XML数据

<?xml version='1.0' encoding='UTF-8'?> 
<feed> 
    <category scheme='http://schemas.google.com/g/2005#kind'/> 
</feed> 

不工作数据(注:在根元素 “进” 属性 “的xmlns”)

<?xml version='1.0' encoding='UTF-8'?> 
<feed xmlns='http://www.w3.org/2005/Atom' > 
    <category scheme='http://schemas.google.com/g/2005#kind'/> 
</feed> 
+0

我已更新标题,希望能更好地反映您的问题(随时恢复/编辑)。下一次,请在普通桌面版上尝试使用相同的代码,以避免添加额外的标签(如windows-phone-7),这些标签可能会让人们试图回答的问题混淆。 –

回答

1

欢迎来到XML命名空间的世界!问题不在于“有一个属性”这一事实,而是因为它导致它下面的所有内容都位于命名空间中。您不能再说.Attribute("scheme"),因为它只能查找空白名称空间中的内容。名称空间是通过基于运算符重载一个玩意儿使用:

XNamespace atom = "http://www.w3.org/2005/Atom'"; 

// And now you can say: 

.Descendants(atom + "feed") 
.Attribute(atom + "scheme") 

等等。将字符串分配给XNamespace变量的能力得益于隐式转换运算符。该+这里实际上构造了一个的XName(其中,顺便说一下,也有从字符串的隐式转换 - 这就是为什么你平原.Elements("feed")作品即使参数类型不是字符串)

手持提示:您可以施放属性为某些类型而不是使用.Value,例如(string)foo.Attribute(atom + "scheme")。它也适用于其他一些类型,例如int