简体   繁体   English

需要帮助将DataTable转换为XML VB.NET

[英]Need help converting DataTable to XML VB.NET

I need help converting DataTable to XML. 我需要将DataTable转换为XML的帮助。 I have done it using LINQ but I can't get exactly as I have to. 我已经使用LINQ做到了,但是我不能完全做到。 I made a picture so that you can easily understand. 我做了一张照片,以便您可以轻松理解。 The XML needs to be in certain format like below so I can't just use dt.writexml(). XML必须采用以下特定格式,因此我不能仅使用dt.writexml()。 Artist ID needs to auto number. 艺术家ID需要自动编号。 Songs are groupped by Artist. 歌曲按艺术家分组。 Prefer a solution in Linq coz that's what I have used throughout the project but I coundn't manage to get what I want here. 在Linq coz中更喜欢一个解决方案,这是我在整个项目中一直使用的解决方案,但我无法在这里得到想要的解决方案。 The columns names are known so you can use something like this in the code. 列名是已知的,因此您可以在代码中使用类似的名称。 row.Field(Of String)("title") row.Field(Of String)(“ title”)

Thanks a lot . 非常感谢 。 I mean it. 我是认真的。 Sorry for poor english. 对不起,英语不好。

在此处输入图片说明

CreateDatatable - this simple code should create a datatable CreateDatatable-这个简单的代码应该创建一个数据表

            Dim dTable As New DataTable
            dTable.Columns.Add("Title")
            dTable.Columns.Add("Artist")
            dTable.Columns.Add("Album")

            dTable.Rows.Add("Baby one more time", "Britney Spears", "Baby one more time")
            dTable.Rows.Add("Crazy", "Britney Spears", "Best of")
            dTable.Rows.Add("Every time", "Britney Spears", "Best of")
            dTable.Rows.Add("Black and White", "Michael Jackson", "Best of")
            dTable.Rows.Add("You are not alone", "Michael Jackson", "Best of")
            dTable.Rows.Add("Smile", "Michael Jackson", "Best of")

what I have at the moment. 我现在有什么 It will convert it datatable to xml without the groupping and album index. 它将没有分组和相册索引的数据表转换为xml。

      Dim xmlDoc As New XDocument(
      From row In dt.Rows
      Select XElement("SONG",
      From column In dt.Columns
            Select
                New XAttribute(column.Name, row.Item(column.Name))
             )
      )

well .. i also have some more code .. that will query first created xml and do the grouping but still having album="albumname" in the song element as attribute. 好..我也有更多的代码..将查询首先创建的xml并进行分组,但仍将song元素中的album =“ albumname”作为属性。 And it should be just one query from datatable to xml .. i hate having to query against xml again to just refomat it. 它应该只是从数据表到xml的一个查询。我讨厌不得不再次针对xml进行查询以重新格式化它。

    Dim replacement = New XDocument(New XElement("root", 
    original.Descendants("Song")
    .GroupBy(Function(x) Convert.ToString(x.Element("artist").value))
    .[Select](Function(songsForArtist, index) 
     New XElement("artist", New XAttribute("id", index + 1),
     New XAttribute("name", songsForArtist.Key), songsForArtist))))

I hope you can convert it to VB.NET 希望您可以将其转换为VB.NET

    using System;
    using System.Linq;
    using System.Data;
    using System.Xml.Linq;

    namespace ConsoleApplication3
    {
        class Program
        {
            static void Main(string[] args)
            {
                var dTable = new DataTable();
                dTable.Columns.Add("Title");
                dTable.Columns.Add("Artist");
                dTable.Columns.Add("Album");

                dTable.Rows.Add("Baby one more time", "Britney Spears", "Baby one more time");
                dTable.Rows.Add("Crazy", "Britney Spears", "Best of");
                dTable.Rows.Add("Every time", "Britney Spears", "Best of");
                dTable.Rows.Add("Black and White", "Michael Jackson", "Best of");
                dTable.Rows.Add("You are not alone", "Michael Jackson", "Best of");
                dTable.Rows.Add("Smile", "Michael Jackson", "Best of");

                var query = dTable.AsEnumerable().
                    GroupBy(row => row.Field<string>("Artist")).
                    Select(
                        (grp, i) => new XElement("Artist",
                            new XAttribute("ID", i + 1),
                            new XAttribute("ARTISTNAME", grp.Key),
                                grp.Select(song => new XElement("SONG",
                                    new XAttribute("artistID", i + 1),
                                    new XAttribute("title", song.Field<string>("Title")),
                                    new XAttribute("album", song.Field<string>("Album"))
                                    )
                                )
                        )
                    );

                var xml = new XElement("Music", query);
            }
        }
    }

you can use the dotnet typed dataset for this. 您可以为此使用dotnet类型的数据集。 the dataset has methods to load and save its content from/to xml. 数据集具有从xml加载和保存其内容的方法。

this xsd will give you the desired xml-format with autoincrement id-s nested subtable and xml-attributes instead of xml-elements for the tablefields. 此xsd将为您提供所需的xml格式,其中包含autoincrement id-s嵌套子表和xml-attributes,而不是tablefields的xml-elements。

add this to you project and generate a typed dataset out of it. 将其添加到您的项目中,并从中生成类型化的数据集。

    <xs:schema id="Music" xmlns="" xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata" xmlns:msprop="urn:schemas-microsoft-com:xml-msprop">
      <xs:element name="Music" msdata:IsDataSet="true" msdata:Locale="en-US">
        <xs:complexType>
          <xs:choice minOccurs="0" maxOccurs="unbounded">
            <xs:element name="Artist">
              <xs:complexType>
                <xs:sequence>
                  <xs:element name="Song" minOccurs="0" maxOccurs="unbounded">
                     <xs:annotation>
                        <xs:appinfo>
                           <msdata:Relationship name="SongsOfArtist" msdata:parent="Artist" msdata:child="Song" msdata:parentkey="ID" msdata:childkey="artistid" msprop:Generator_UserRelationName="SongsOfArtist" msprop:Generator_RelationVarName="relationSongsOfArtist" msprop:Generator_UserChildTable="Song" msprop:Generator_UserParentTable="Artist" /></xs:appinfo></xs:annotation>
                    <xs:complexType>
                      <xs:attribute name="SongID" msdata:AutoIncrement="true" msdata:AutoIncrementSeed="1" type="xs:long" msdata:AllowDBNull="false" use="prohibited" />
                      <xs:attribute name="artistid" msdata:AutoIncrementSeed="1" type="xs:long" use="required" />
                      <xs:attribute name="title" msprop:DateTimeMode="UnspecifiedLocal" type="xs:string" />
                      <xs:attribute name="album" msprop:DateTimeMode="UnspecifiedLocal" type="xs:string" />
                    </xs:complexType>
                  </xs:element>
                </xs:sequence>
                <xs:attribute name="ID" msdata:AutoIncrement="true" msdata:AutoIncrementSeed="1" type="xs:long" use="required" />
                <xs:attribute name="ARTISTNAME" msprop:DateTimeMode="UnspecifiedLocal" type="xs:string" />
              </xs:complexType>
            </xs:element>
          </xs:choice>
        </xs:complexType>
        <xs:unique name="Song_Constraint1" msdata:ConstraintName="Constraint1">
          <xs:selector xpath=".//Song" />
          <xs:field xpath="@SongID" />
        </xs:unique>
        <xs:unique name="Constraint2">
          <xs:selector xpath=".//Song" />
          <xs:field xpath="@artistid" />
        </xs:unique>
        <xs:unique name="Constraint1">
          <xs:selector xpath=".//Artist" />
          <xs:field xpath="@ID" />
        </xs:unique>
        <xs:keyref name="SongsOfArtist" refer="Constraint1" msdata:IsNested="true">
          <xs:selector xpath=".//Song" />
          <xs:field xpath="@artistid" />
        </xs:keyref>
      </xs:element>
    </xs:schema>

i am not shure if the vs2010 xsd editor still supports all xsd-settings in this file. 我不知道vs2010 xsd编辑器是否仍然支持此文件中的所有xsd设置。 Maybes some settings get lost if you edit it with vs 2010. with vs2003-xsd editor it works. 如果使用vs 2010进行编辑,可能会丢失某些设置。使用vs2003-xsd编辑器可以正常工作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM