これは、LINQ to XML の奇妙な動作です。これは参照 XML ドキュメントです。
<Root>
<First>first</First>
<Second></Second>
<Third />
</Root>
ご想像のとおりですroot.Element("First").Value == "first"。
ご想像のとおりですroot.Element("Second").Value == ""。
私はそうなると期待root.Element("Third").Valueしますnull。しかし、ここに問題があります:root.Element("Third ").Value空の文字列を返します。
.NET フレームワークのソース コードは次のとおりです。
public string Value
{
get
{
if (this.content == null)
{
return string.Empty;
}
string text = this.content as string;
if (text != null)
{
return text;
}
StringBuilder stringBuilder = new StringBuilder();
this.AppendText(stringBuilder);
return stringBuilder.ToString();
}
私の期待は明らかに間違っていますか?これは間違った設計上の決定ですか?return nullの代わりに aと書いたでしょうreturn string.Empty。
IsEmptyタグが開いているか自己閉じているかを示すプロパティがあることに注意してください。