从xml文件构建类

时间:2014-09-02 07:54:21

标签: c# xml

首先,对不起,我知道我的问题将是非常基本的,但我会非常感谢一些帮助,我承受着很大的压力,所以做出明智的评论和具有讽刺意味不会帮助

我有这个代码: 至少我在尝试。 我有这个xml文件,我需要在类中保存它的所有属性,这样我就可以随时复制它。

我不知道该怎么做。

public static void firstFileXml(string sXml1)
{
    var root = XElement.Load(@"sXml1");
    var controlElementsFirst = root.Descendants("books");
}

XML文件具有以下属性:label,text,label_w等。 我需要一个能让我输入的函数或者一些东西: 探索(xmlLocation)并完成其余的工作。 因为我需要为几个xml文件执行此操作

我需要构建一个允许我阅读它的类。 假设我有这个xml文件:

WAS

    <books>
        <book label='' page='' intro =''/>
        <book label='' page='' intro =''/>
        <book label='' page='' intro =''/>
    </books>

IS

<SHEET>
<books>
<book label='1' page='1' intro='1'/>
<book label='2' page='2' intro='2'/>
<book label='3' page='3' intro='3'/>
</books>
</SHEET>

等等。 我首先要读取这个xml文件,然后将书籍属性存储在一个类中,这样我以后就可以将它用于数百本书

代码:

using System;
using System.Collections.Generic;
using System.IO;
using System.Xml.Serialization;

static class Program
{
    static void Main()
    {
        // get the xml as a string; note that we could also use
        // Deserialize(Stream) to process a FileStream, but this
        // works fine
        string xml = File.ReadAllText(@"C:\Users\books.xml");
        var ser = new XmlSerializer(typeof(BookRoot));
        var root = (BookRoot)ser.Deserialize(new StringReader(xml));
        foreach (var book in root.Books)
        {
            Console.WriteLine("label: " + book.Label);
            Console.WriteLine("page: " + book.Page);
            Console.WriteLine("intro: " + book.Intro);
            Console.ReadLine();
        }
    }
}
[XmlRoot("SHEET")]
public class BookRoot
{
    private readonly List<Book> books = new List<Book>();
    [XmlArray("books"), XmlArrayItem("book")]
    public List<Book> Books { get { return books; } }
}
public class Book
{
    [XmlAttribute("label")]
    public string Label { get; set; }
    [XmlAttribute("page")]
    public string Page { get; set; }
    [XmlAttribute("intro")]
    public string Intro { get; set; }
}

1 个答案:

答案 0 :(得分:4)

在命令行:

xsd yourfile.xml
xsd /c yourfile.xsd

这将使用xml作为模板创建C#类(通过模式推理);然后,您可以使用XmlSerializer的那些类,即

var ser = new XmlSerializer(typeof(YourRootType));
YourRootType root = (YourRootType)ser.Deserialize(source);
Console.WriteLine(root.Foo);
foreach(Bar bar in root.Bars) {
    Console.WriteLine(bar.Name);
    Console.WriteLine(bar.Id);
}

例如,使用:

<books>
<book label='' page='' intro=''/>
<book label='' page='' intro=''/>
<book label='' page='' intro=''/>
</books>

这会生成架构:

<?xml version="1.0" encoding="utf-8"?>
<xs:schema id="books" xmlns="" xmlns:xs="http://www.w3.org/2001/XMLSchema"
    xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
  <xs:element name="books" msdata:IsDataSet="true" msdata:Locale="en-US">
    <xs:complexType>
      <xs:choice minOccurs="0" maxOccurs="unbounded">
        <xs:element name="book">
          <xs:complexType>
            <xs:attribute name="label" type="xs:string" />
            <xs:attribute name="page" type="xs:string" />
            <xs:attribute name="intro" type="xs:string" />
          </xs:complexType>
        </xs:element>
      </xs:choice>
    </xs:complexType>
  </xs:element>
</xs:schema>

然后是C#代码:

//------------------------------------------------------------------------------
// <auto-generated>
//     This code was generated by a tool.
//     Runtime Version:4.0.30319.34014
//
//     Changes to this file may cause incorrect behavior and will be lost if
//     the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------

using System.Xml.Serialization;

// 
// This source code was auto-generated by xsd, Version=4.0.30319.18020.
// 


/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.0.30319.18020")]
[System.SerializableAttribute()]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType=true)]
[System.Xml.Serialization.XmlRootAttribute(Namespace="", IsNullable=false)]
public partial class books {

    private booksBook[] itemsField;

    /// <remarks/>
    [System.Xml.Serialization.XmlElementAttribute("book", Form=System.Xml.Schema.XmlSchemaForm.Unqualified)]
    public booksBook[] Items {
        get {
            return this.itemsField;
        }
        set {
            this.itemsField = value;
        }
    }
}

/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.0.30319.18020")]
[System.SerializableAttribute()]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType=true)]
public partial class booksBook {

    private string labelField;

    private string pageField;

    private string introField;

    /// <remarks/>
    [System.Xml.Serialization.XmlAttributeAttribute()]
    public string label {
        get {
            return this.labelField;
        }
        set {
            this.labelField = value;
        }
    }

    /// <remarks/>
    [System.Xml.Serialization.XmlAttributeAttribute()]
    public string page {
        get {
            return this.pageField;
        }
        set {
            this.pageField = value;
        }
    }

    /// <remarks/>
    [System.Xml.Serialization.XmlAttributeAttribute()]
    public string intro {
        get {
            return this.introField;
        }
        set {
            this.introField = value;
        }
    }
}

适用于XmlSerializer,可以正确反序列化您的数据,例如:

var ser = new XmlSerializer(typeof(books));
var root = (books)ser.Deserialize(new StringReader(xml));
foreach(var book in root.Items)
{
    Console.WriteLine("label: " + book.label);
    Console.WriteLine("page: " + book.page);
    Console.WriteLine("intro: " + book.intro);
}

请注意,您可以手动轻松完成:

[XmlRoot("books")]
public class BookRoot {
    private readonly List<Book> books = new List<Book>();
    [XmlElement("book")]
    public List<Book> Books { get { return books; } }
}
public class Book {
    [XmlAttribute("label")]
    public string Label {get;set;}
    [XmlAttribute("page")]
    public string Page {get;set;}
    [XmlAttribute("intro")]
    public string Intro {get;set;}
}

例如:

var ser = new XmlSerializer(typeof(BookRoot));
var root = (BookRoot)ser.Deserialize(new StringReader(xml));
foreach(var book in root.Books)
{
    Console.WriteLine("label: " + book.Label);
    Console.WriteLine("page: " + book.Page);
    Console.WriteLine("intro: " + book.Intro);
}

使用最新的编辑在XML中添加级别,属性需要稍微调整一下 - 更改根元素名称,并添加其他级别(books/book =&gt; SHEET/books/book ):

[XmlRoot("SHEET")]
public class BookRoot
{
    private readonly List<Book> books = new List<Book>();
    [XmlArray("books"), XmlArrayItem("book")]
    public List<Book> Books { get { return books; } }
}