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="" />

しかし、先に進む方法がわかりません。ラインがスラッシュで終わっていることがわかりました/。ありがとうございます。

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)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ドキュメントに複数の要素を書き込む予定で、それらがArrayListまたはその他の中にあるIEnumerable場合は、以下のコードのようなものを使用して、それらをすべて吐き出すことができます。

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 に答える