【问题标题】:XML reader can't find elements when using xmlns attribute使用 xmlns 属性时 XML 阅读器找不到元素
【发布时间】:2012-12-30 23:18:29
【问题描述】:

我正在使用 Visual Studio for Windows Phone,当 XML 数据的父级中有属性时,我的 XML 阅读器代码不起作用。

我的 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>

不是工作数据(注意:根元素“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>

【问题讨论】:

  • 我已经更新了标题,希望能更好地反映您的问题(随时恢复/编辑)。下次请在常规桌面版本上尝试相同的代码,以避免添加额外的标签(如 windows-phone-7),这可能会使试图回答的人感到困惑。

标签: c# xml linq


【解决方案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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-03-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-10-17
    • 1970-01-01
    相关资源
    最近更新 更多