共用方式為


如何:建立 XML 常值 (Visual Basic)

您可以使用 XML 常值,直接在程式碼中建立 XML 文件、片段或元素。 本主題中範例示範如何建立具有三個子項目的 XML 元素,以及如何建立 XML 文件。

您也可以使用 LINQ to XML API 來建立 LINQ to XML 物件。 如需詳細資訊,請參閱XElement

建立 XML 元素

  • 使用 XML 常值語法建立 XML 內嵌,這與實際的 XML 語法相同。

    Dim contact1 As XElement = 
        <contact>
          <name>Patrick Hines</name>
          <phone type="home">206-555-0144</phone>
          <phone type="work">425-555-0145</phone>
        </contact>
    

    執行程式碼。 此程式碼的輸出如下:

    <contact>

    <name>Patrick Hines</name>

    <phone type="home">206-555-0144</phone>

    <phone type="work">425-555-0145</phone>

    </contact>

建立 XML 文件

  • 建立 XML 文件內嵌。 下列程式碼會建立 XML 文件,其中包含常值語法、XML 宣告、處理指示、註解,以及包含另一個元素的元素。

    Dim libraryRequest As XDocument = 
        <?xml version="1.0" encoding="UTF-8" standalone="yes"?>
        <?xml-stylesheet type="text/xsl" href="show_book.xsl"?>
        <!-- Tests that the application works. -->
        <books>
            <book/>
        </books>
    Console.WriteLine(libraryRequest)
    

    執行程式碼。 此程式碼的輸出如下:

    <?xml-stylesheet type="text/xsl" href="show_book.xsl"?>

    <!-- Tests that the application works. -->

    <books>

    <book/>

    </books>

另請參閱