0

Windows Phone に Visual Studio を使用していますが、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>
4

1 に答える 1

1

XML 名前空間の世界へようこそ! 問題は、「属性がある」という事実ではなく、その下のすべてが名前空間にあるという事実です。.Attribute("scheme")空の名前空間内のものしか検索しないため、もはや言うことはできません。名前空間は、演算子のオーバーロードに基づく仕掛けを介して使用されます。

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

// And now you can say:

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

など。文字列を XNamespace 変数に割り当てる機能は、暗黙的な変換演算子のおかげです。hereは+実際に XName を構築します(ちなみに、これには文字列からの暗黙的な変換もあります-そのため.Elements("feed")、パラメーターの型が文字列でなくても、プレーンに機能します)

.Value便利なヒント:たとえば、を使用する代わりに、属性を特定のタイプにキャストできます(string)foo.Attribute(atom + "scheme")。など、他の多くのタイプでも機能しますint

于 2012-12-30T23:22:48.123 に答える