将XML数据读入c#应用程序

时间:2021-11-01 16:55:29

I need to create an xml file that is supposed to look like this.

我需要创建一个看起来像这样的xml文件。

<Event id="Date - Event Name - Event Type">      
    <DogNumber id="dog id number">           
        <dogName id-"dog id number">dog name</dogName>               
        <dogBreed>dog breed</dogBreed>      
    </DogNumber>
</Event>

and then it would repeat again for another event except for different values and attributes for the elements.

然后它会对另一个事件重复,除了元素的不同值和属性。

<Event id="Date - Event Name - Event Type">      
    <DogNumber id="dog id number">           
        <dogName id-"dog id number">dog name</dogName>               
        <dogBreed>dog breed</dogBreed>      
    </DogNumber>
</Event>

I am new to creating XML files with C# and am having trouble properly adding the attributes to the element and getting the parent and child nodes the same as I have shown above. I need to be able to look into this file from my C# application and be able to read all of the values listed above based on the particular event and then the particular dog in each event. The criteria of which event and which dog to select will be based upon user input in a ComboBox likely. my plan was to use the getElementById method. However, I have seen so many different ways to do this that I am having trouble deciding what would be the best and most efficient way to do this.

我是使用c#创建XML文件的新手,在正确地向元素添加属性和获得父节点和子节点方面遇到了麻烦,就像上面所示的那样。我需要能够从c#应用程序中查看这个文件,并能够根据特定事件和每个事件中的特定dog读取上面列出的所有值。选择哪一个事件和哪只狗将取决于用户在组合框中的输入。我的计划是使用getElementById方法。然而,我已经看到了很多不同的方法来做这件事,我很难决定什么是最好和最有效的方法来做这件事。

5 个解决方案

#1


4  

I think easiest method to read/write that xml file would be using XMLSerializer. This approach also enable You to easly bind to data (if You are using WPF for UI)

我认为读取/写入xml文件的最简单方法是使用XMLSerializer。这种方法还使您能够轻松地绑定到数据(如果您在UI中使用WPF)

Create serializable classes:

创建可序列化的类:

    public class Event
    {
        [XmlAttribute]
        public string id { get; set; }

        [XmlElement]
        public DogNumber DogNumber { get; set; }
    }

    public class DogNumber
    {
        [XmlAttribute]
        public string id { get; set; }

        [XmlElement]
        public dogName dogName { get; set; }

        [XmlElement]
        public string dogBreed { get; set; }
    }

    public class dogName
    {
        [XmlAttribute]
        public string id { get; set; }

        [XmlTextAttribute]
        public string value { get; set;  }
    }

and then use XmlSerializer to deserialize(example using file):

然后使用XmlSerializer反序列化(例如使用文件):

        Stream input = File.OpenRead("C:\\test.xml");
        XmlSerializer serialier = new XmlSerializer(typeof(Event));
        Event newevent = serialier.Deserialize(input) as Event;
        input.Close();

#2


2  

Check LINQ to XML.

检查LINQ to XML。

Here is a very quick overview

这是一个非常快速的概述

msdn

msdn

#3


0  

I am finding the best method for my needs when it comes to XML is to serialize/deserialize using classes.

当涉及到XML时,我发现最好的方法是使用类进行序列化/反序列化。

For example, take the following code:

例如,取以下代码:

/// <summary>
/// Details on the destination of the shipment.
/// </summary>
[XmlRoot("destination")]
public class Destination
{
    List<Recipient> recipient { get; set; }
}

/// <summary>
/// Recipient details.
/// </summary>
[XmlRoot("recipient")]
public class Recipient
{

    /// <summary>
    /// Client Id of the recipient; only used if selected as the sort criterion.
    /// </summary>
    /// <remarks>Truncated after 30 characters.</remarks>        
    [XmlElement("client-id")]
    public string ClientID { get; set; } 

    /// <summary>
    /// Name of the individual receiving the shipment.
    /// </summary>
    /// <remarks>Truncated after 44 characters.</remarks>
    [XmlElement("contact-name")]
    public string ContactName { get; set; } 

    /// <summary>
    /// Name of the company.
    /// </summary>
    /// <remarks>Truncated after 44 characters.</remarks>
    [XmlElement("company")]
    public string Company { get; set; }

    ...

This will allow me to serialize the object into XML that looks like this:

这将允许我将对象序列化为如下所示的XML:

<destination>
     <recipient>
         <client-id></client-id>
         <contact-name></contact-name>
         <company></company>
         ...

I can control how the XML is created by using the XmlRoot or XmlElement modifiers. In your case you can use the [XmlAttribute("attributeName")] to specify attributes.

我可以通过使用XmlRoot或XmlElement修饰符来控制如何创建XML。在您的示例中,可以使用[XmlAttribute(“attributeName”)]来指定属性。

You can read more about the various XML modifiers here: http://msdn.microsoft.com/en-us/library/e123c76w.

您可以在这里阅读更多关于各种XML修饰符的信息:http://msdn.microsoft.com/en-us/library/e123c76w。

#4


0  

In C# for create or read XML, you want to use XDocument class (you have sample of use in end of this msdn website)

在c#中创建或读取XML时,您希望使用XDocument类(在此msdn网站的末尾有使用示例)

XDocument yourXml = null;

after your treatment ( add node, etc...) if you want, you want to save your xml in file.xml

在您的处理(添加节点等)之后,如果您愿意,您希望将xml保存在file.xml中

// verify if file not existing
if (!System.IO.File.Exists(@"yourName.xml"))
{
    // if file not exist, create xml file.
    FileStream fs = File.Create(@"yourName.xml");
    fs.Close();
}

// save your xml in xml file
yourXml.Save(@"yourName.xml");

#5


0  

You can try using XDocument like:

您可以尝试使用XDocument,如:

XDocument doc = new XDocument(new XElement("Event", new XAttribute("Id", youEventString),
    new XElement("DogNumber", new XAttribute("id", dogId),
    new XElement("dogName", new XAttribute("id", dogNumber), dogNname),
    new XElement("dogBreed", dogBreed)  
    )));
doc.Save(filename);

Where you can substitute youEventString, dogId, dogNumber, dogName, dogBreed with the appropriate strings. Also provide filename where the file to be saved.

你可以用适当的字符串替换youEventString、dogId、dogNumber、dogName、dogBreed。还要提供要保存的文件的文件名。

Good luck

祝你好运

#1


4  

I think easiest method to read/write that xml file would be using XMLSerializer. This approach also enable You to easly bind to data (if You are using WPF for UI)

我认为读取/写入xml文件的最简单方法是使用XMLSerializer。这种方法还使您能够轻松地绑定到数据(如果您在UI中使用WPF)

Create serializable classes:

创建可序列化的类:

    public class Event
    {
        [XmlAttribute]
        public string id { get; set; }

        [XmlElement]
        public DogNumber DogNumber { get; set; }
    }

    public class DogNumber
    {
        [XmlAttribute]
        public string id { get; set; }

        [XmlElement]
        public dogName dogName { get; set; }

        [XmlElement]
        public string dogBreed { get; set; }
    }

    public class dogName
    {
        [XmlAttribute]
        public string id { get; set; }

        [XmlTextAttribute]
        public string value { get; set;  }
    }

and then use XmlSerializer to deserialize(example using file):

然后使用XmlSerializer反序列化(例如使用文件):

        Stream input = File.OpenRead("C:\\test.xml");
        XmlSerializer serialier = new XmlSerializer(typeof(Event));
        Event newevent = serialier.Deserialize(input) as Event;
        input.Close();

#2


2  

Check LINQ to XML.

检查LINQ to XML。

Here is a very quick overview

这是一个非常快速的概述

msdn

msdn

#3


0  

I am finding the best method for my needs when it comes to XML is to serialize/deserialize using classes.

当涉及到XML时,我发现最好的方法是使用类进行序列化/反序列化。

For example, take the following code:

例如,取以下代码:

/// <summary>
/// Details on the destination of the shipment.
/// </summary>
[XmlRoot("destination")]
public class Destination
{
    List<Recipient> recipient { get; set; }
}

/// <summary>
/// Recipient details.
/// </summary>
[XmlRoot("recipient")]
public class Recipient
{

    /// <summary>
    /// Client Id of the recipient; only used if selected as the sort criterion.
    /// </summary>
    /// <remarks>Truncated after 30 characters.</remarks>        
    [XmlElement("client-id")]
    public string ClientID { get; set; } 

    /// <summary>
    /// Name of the individual receiving the shipment.
    /// </summary>
    /// <remarks>Truncated after 44 characters.</remarks>
    [XmlElement("contact-name")]
    public string ContactName { get; set; } 

    /// <summary>
    /// Name of the company.
    /// </summary>
    /// <remarks>Truncated after 44 characters.</remarks>
    [XmlElement("company")]
    public string Company { get; set; }

    ...

This will allow me to serialize the object into XML that looks like this:

这将允许我将对象序列化为如下所示的XML:

<destination>
     <recipient>
         <client-id></client-id>
         <contact-name></contact-name>
         <company></company>
         ...

I can control how the XML is created by using the XmlRoot or XmlElement modifiers. In your case you can use the [XmlAttribute("attributeName")] to specify attributes.

我可以通过使用XmlRoot或XmlElement修饰符来控制如何创建XML。在您的示例中,可以使用[XmlAttribute(“attributeName”)]来指定属性。

You can read more about the various XML modifiers here: http://msdn.microsoft.com/en-us/library/e123c76w.

您可以在这里阅读更多关于各种XML修饰符的信息:http://msdn.microsoft.com/en-us/library/e123c76w。

#4


0  

In C# for create or read XML, you want to use XDocument class (you have sample of use in end of this msdn website)

在c#中创建或读取XML时,您希望使用XDocument类(在此msdn网站的末尾有使用示例)

XDocument yourXml = null;

after your treatment ( add node, etc...) if you want, you want to save your xml in file.xml

在您的处理(添加节点等)之后,如果您愿意,您希望将xml保存在file.xml中

// verify if file not existing
if (!System.IO.File.Exists(@"yourName.xml"))
{
    // if file not exist, create xml file.
    FileStream fs = File.Create(@"yourName.xml");
    fs.Close();
}

// save your xml in xml file
yourXml.Save(@"yourName.xml");

#5


0  

You can try using XDocument like:

您可以尝试使用XDocument,如:

XDocument doc = new XDocument(new XElement("Event", new XAttribute("Id", youEventString),
    new XElement("DogNumber", new XAttribute("id", dogId),
    new XElement("dogName", new XAttribute("id", dogNumber), dogNname),
    new XElement("dogBreed", dogBreed)  
    )));
doc.Save(filename);

Where you can substitute youEventString, dogId, dogNumber, dogName, dogBreed with the appropriate strings. Also provide filename where the file to be saved.

你可以用适当的字符串替换youEventString、dogId、dogNumber、dogName、dogBreed。还要提供要保存的文件的文件名。

Good luck

祝你好运