2

確かに、それは簡単な質問ですが、私は本当のあいまいさを念頭に置いており、解決策を見つけることができません.

次のような非常に単純なxmlがあります。

  <xml-header>
   <error code="40" message="errorMessage" /> 
  </xml-header>

そして、そこから値「40」を取得する必要があります。したがって、私の意見では、要素「エラー」の属性「コード」から値を取得します。(私は正しいですか?)

return (from node in xdoc.Descendants() select node.Element("error").Attribute("code").Value).First();

そして、それはうまくいきません。正しい表現は?


[アップデート]

申し訳ありませんが、問題は xNamespace にありました。

したがって、次のようになるはずxdoc.Descendants(Constants.xNamespace) です。定数クラスにもこれがありました。

4

3 に答える 3

3

子孫エラー要素を選択します。要素にそのような属性がない場合に例外を取得したくない場合は、Value プロパティの使用も避けてください。

(from node in xdoc.Descendants("error") 
 select (int)node.Attribute("code"))
 .First();

メソッド構文も使用できます。

xdoc.Descendants("error")
    .Select(e => (int)e.Attribute("code"))
    .First()

注意してください - シーケンスに要素が含まれていない場合、First は例外をスローします。そのエラーを回避したい場合は、FirstOrDefault代わりに使用してください。名前空間が定義されている場合は、要素を選択するときにそれを使用します。

XNamespace ns = "http://someAdress";
xdoc.Descendants(ns + "error")
于 2013-02-11T12:49:02.737 に答える
1

次のようなものを試してください(すべてのエラー処理は省略されています!):

using System;
using System.IO;
using System.Xml.Linq;
using System.Xml.XPath;

namespace Demo
{
    public static class Program
    {
        private static void Main(string[] args)
        {
            string xml = "<xml-header><error code=\"40\" message=\"errorMessage\" /></xml-header>";

            var element = XElement.Load(new StringReader(xml));
            var errorElement = element.XPathSelectElement("error");
            string code = errorElement.Attribute("code").Value;

            Console.WriteLine(code); // Prints 40
        }
    }
}

または、XDocumentを使用し、拡張機能を回避します。

using System;
using System.IO;
using System.Xml.Linq;

namespace Demo
{
    public static class Program
    {
        private static void Main(string[] args)
        {
            string xml = "<xml-header><error code=\"40\" message=\"errorMessage\" /></xml-header>";

            var doc = XDocument.Load(new StringReader(xml));

            var errorElement = doc.Element("xml-header").Element("error");
            string code = errorElement.Attribute("code").Value;

            Console.WriteLine(code);  // Prints 40
        }
    }
}
于 2013-02-11T12:27:31.193 に答える
1

You already have error element in descendants. Try this:

return xdoc.Descendants().Select(n => n.Attribute("code").Value).First();

or this, if you like query style:

return (from node in xdoc.Descendants() select node.Attribute("code").Value).First();
于 2013-02-11T12:28:19.387 に答える