0

我想写一个如下的 XML 文件:

<?xml version="1.0" encoding="UTF-8"?>
<books xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
  <License licenseId="" licensePath="" />

我的一些代码附在这里

    // Create a new file in D:\\ and set the encoding to UTF-8
    XmlTextWriter textWriter = new XmlTextWriter("D:\\books.xml", System.Text.Encoding.UTF8);

    // Format automatically
    textWriter.Formatting = Formatting.Indented;

    // Opens the document
    textWriter.WriteStartDocument();

    // Write the namespace declaration.
    textWriter.WriteStartElement("books", null);
    // Write the genre attribute.
    textWriter.WriteAttributeString("xmlns", "xsd", null, "http://www.w3.org/2001/XMLSchema");
    textWriter.WriteAttributeString("xmlns", "xsi", null, "http://www.w3.org/2001/XMLSchema-instance");

现在我需要用 C# 编写下面的许可证行

<License licenseId="" licensePath="" />

但我不知道如何继续,因为我发现 Line 以正斜杠/结尾。谢谢。

4

3 回答 3

2

关于你这样做的方式,我有 2 个问题:

1)你必须使用文本作家吗?如果您有权访问 c# 3.0,则可以使用以下内容:

XDocument doc = new XDocument(
    new XDeclaration("1.0", "utf-8", "yes"),
    new XAttribute(XNamespace.Xmlns + "xsd", "http://www.w3.org/2001/XMLSchema"),
    new XAttribute(XNamespace.Xmlns + "xsi", "http://www.w3.org/2001/XMLSchema-instance"),
    new XElement("Equipment",
        new XElement("License", 
            new XAttribute("licenseId", ""), 
            new XAttribute("licensePath", "")
        )
    )
);

2) 你必须声明这两个命名空间吗?在我看来,您不会使用它们:

XDocument doc = new XDocument(
    new XDeclaration("1.0", "utf-8", "yes"),
    new XElement("Equipment",
        new XElement("License", 
            new XAttribute("licenseId", ""), 
            new XAttribute("licensePath", "")
        )
    )
);

如果您打算将多个License元素写入文档,并且将它们放在或其他中Array,则可以使用类似于以下代码的内容将它们全部吐出:ListIEnumerable

IEnumerable<LicenceObjects> licenses = //some code to make them;

XDocument doc = new XDocument(
    new XDeclaration("1.0", "utf-8", "yes"),
    new XElement("Equipment",
        licenses.Select(l => 
            new XElement("License", 
                new XAttribute("licenseId", l.licenseId), 
                new XAttribute("licensePath", l.licensePath)
            )
        )
    )
);

string xmlDocumentString = doc.ToString();

当然,如果您没有 .NET 3.0,那么这对您毫无用处 :(

于 2010-03-25T09:21:20.180 回答
1

调用 WriteEndElement 方法将自动处理添加正斜杠。

于 2010-03-25T09:21:07.730 回答
1

你为什么不像开始那样继续?

textWriter.WriteStartElement("Licence");
textWriter.WriteAttributeString("LicenseId", "");
textWriter.WriteAttributeString("LicensePath", "");

// Other stuff
textWriter.WriteEndDocument();
textWriter.Close();
于 2010-03-25T09:25:17.367 回答