1

これは私の現在の XML 構造です

<root>
<sublist>
    <sub a="test" b="test" c="test"></sub>
  </sublist>
</root>

次のC#を使用していますが、実行しようとするとエラーが発生します

 public static void writeSub(string a,string b,string c)
        {
            XDocument xDoc = XDocument.Load(sourceFile);
            XElement root = new XElement("sub");
            root.Add(new XAttribute("a", a), new XAttribute("b", b),
                         new XAttribute("c", c));
            xDoc.Element("sub").Add(root);
            xDoc.Save(sourceFile);
        }

どこを間違えますか?

エラーは

nullreferenceexception was unhandled
4

1 に答える 1

0

subドキュメントのルート要素ではないため、問題があります。だから、あなたがするとき

xDoc.Element("sub").Add(root);

その後、をxDoc.Element("sub")返しますnullAdd次に、メソッドを呼び出そうとすると、NullReferenceException.

sub要素に新しい要素を追加する必要があると思いますsublist

xDoc.Root.Element("sublist").Add(root);

また、ネーミングを改善することをお勧めします。element を作成している場合は、名前を付ける代わりにsubvaribale を呼び出します(これは非常に紛らわしいです)。例えばsubroot

XDocument xdoc = XDocument.Load(sourceFile);
var sub = new XElement("sub", 
               new XAttribute("a", a), 
               new XAttribute("b", b),
               new XAttribute("c", c));

xdoc.Root.Element("sublist").Add(sub);
xdoc.Save(sourceFile);
于 2014-06-01T19:35:06.117 に答える