【问题标题】:How to automatically fill xml ? linq to xml如何自动填充xml?链接到 xml
【发布时间】:2020-06-30 07:10:51
【问题描述】:

我想使用 Linq(如果可以的话)从数据库中的数据自动创建一个 XML。 为此,我的理解是需要占位符。 你如何插入这些占位符? 我已经向您展示了我的示例 XML,我想保留这种格式。 (除非它不起作用) 我期待您的回答,并在此先感谢您。

 using System;
 using System.Collections.Generic;
 using System.Linq;
 using System.Text;
 using System.Threading.Tasks;
 using System.Xml.Linq;
 using System.Xml.Schema;

 namespace LinqToXML1._1
 {
   class Program
   {
    static void Main(string[] args)
    {
        XDocument exampleDocument= new XDocument(new XDeclaration("1.0", "utf-8", "yes"),
            new XElement("VN_Nr", new XAttribute("VN_Nr(placeholder int)",11),
                new XElement("EI Nubmer" ,3, new XAttribute("NL Number","EI Number(placeholder int) 0000")),
                    new XElement("Serialnumber", 0),
                        new XElement("GM Number(placeholder int)",2),
                         new XElement("FW Number (placeholder string)")
                         )

            ); // Safe file.
        exampleDocument.Save(@"C:");
        Console.WriteLine(exampleDocument.ToString());

    }
}

}

【问题讨论】:

  • 您期望的 XML 是什么?属性不能使用(,它是特殊字符。

标签: .net xml linq


【解决方案1】:

格式良好的 XML 文件只有一个根元素。因此,如果您要从数据库中添加多行,则需要另一个标签来拥有 VN_numbers,其中所有数据都在此标签下。这就是我重写你的代码的方式。您需要 for 循环来添加数据库中的每个新行。我没有包含循环

注意:标签名称和属性名称中不能有空格,所以我修复了这个问题。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Linq;

namespace ConsoleApplication1
{
    class Program
    {
        const string FILENAME = @"c:\temp\test.xml";
        static void Main(string[] args)
        {
            string root = "<?xml version=\"1.0\" encoding=\"utf-8\" standalone=\"yes\"?><VN_Numbers></VN_Numbers>"; 
            XDocument exampleDocument = XDocument.Parse(root);

            XElement vnNumbers = exampleDocument.Descendants("VN_Numbers").FirstOrDefault();

            XElement vnNr = new XElement("VN_Nr", new object[] { 
                    new XAttribute("VN_Nr", 11),
                    new XElement("EI_Nubmer", new object[] {new XAttribute("NL_Number", 0000), 3}),
                    new XElement("Serialnumber", 0),
                    new XElement("GM_Number", 2),
                    new XElement("FW_Number")
            });
            vnNumbers.Add(vnNr);

           exampleDocument.Save(FILENAME);
        }
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-10-24
    • 1970-01-01
    • 2019-11-20
    • 1970-01-01
    • 1970-01-01
    • 2019-03-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多