开发者

Xml.Linq: Add a XNode to a XDocument

I have to export to XML开发者_Python百科 a list of BusinessObjects - myBOs

I worked before with such a tasks, using XmlDocument.

Now, I read that System.Xml.Linq is more flexible to use. So I took XDocument.

Now the logic is the following (pseudo code):

Method ExportBOs(myBOs, fileName) 
  xDoc = New XDocument          ' create
  foreach bo in myBOs
    xDoc.Add(GetMyBOAsNode(bo)) ' build
  xDoc.Save(filename)           ' save


Method GetMyBOAsNode(myBo) as XNode
  result = New XNode(myBo.Name) ' ??? don't work
  Return result      

What is the way to deal with?


You have two problems:

  • XNode is abstract. I suspect you actually want to create an XElement
  • You can't have multiple top-level elements. I suspect you want to create a single root XElement, add it to the document, and then add multiple child elements to that root element.


First you need to have a single root element (multiple roots are not allowed).

Second, use System.Xml.Linq.XElement:

public void ExportBOs(IEnumerable<myBO> myBOs, string fileName)
{
    var root = new XElement("BOs");

    foreach(var bo in myBOs){
        root.Add(new XElement("BO", bo.Name));
    }

    root.Save(filePath);
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜