简体   繁体   English

XML持久性不止一项?

[英]XML persistence more than one item?

Hey I have the following code to Store the data from a list into a XML file, However when I add a 2nd Item to the list it just overwrites the first one in XML so there is only ever one Item in the XML file, How can I solve this 嘿,我有以下代码将列表中的数据存储到XML文件中,但是,当我向列表中添加第二个项目时,它只会覆盖XML中的第一个项目,因此XML文件中只有一个项目,如何我解决了

class

public class Visits
{
/*
 * This class represents a single appointment
 */

    private string Customer_Name;
    private string Customer_Address;
    private DateTime Arrival_Time;
    private string Visit_Type;
    private Double Lat1;
    private Double Long1;
    //Private methods. Note the use of DateTime to store arrival time

    public string name{
        //Description property
        set { Customer_Name = value; }
        get {return Customer_Name;}
    }

    public string address
    {//Time property
        set { Customer_Address = value; }
        get { return Customer_Address; }
    }

    public DateTime arrival
    {   //Duration property
        set { Arrival_Time = value; }
        get { return Arrival_Time; }
    }

    public string type
    {
        set { Visit_Type = value; }
        get { return Visit_Type; }
    }

    public Double Lat
    {
        //Description property
        set { Lat1 = value; }
        get { return Lat1; }
    }

    public Double Lon1
    {
        //Description property
        set { Long1 = value; }
        get { return Long1; }
    } 
    public override string ToString()
    {   //Return a String representing the object
        return Visit_Type + "     " + Customer_Name + " " + Customer_Address + " " + Arrival_Time.ToString() + " " + "Latitude  " + Lat1 + " " + "Longitude  " + Long1;
    }
}

} }

then the list 然后列表

class List
{
/*
 * This object represents the List. It has a 1:M relationship with the Visit class
 */

    private List<Visits> visits = new List<Visits>();
    //List object use to implement the relationshio with Visits

    public void addVisits(Visits vis)
    {
        //Add a new Visit to the List
        visits.Add(vis);
    }

    public List<String> listVisits()
    {//Generate a list of String objects, each one of which represents a Visit in List.

        List<String> listVisits = new List<string>();
        //This list object will be populated with Strings representing the Visits in the lists

        foreach (Visits vis in visits)
        {
            String visAsString = vis.ToString();
            //Get a string representing the current visit object

            listVisits.Add(visAsString);
            //Add the visit object to the List
        }

        return listVisits;
        //Return the list of strings
    }

    public Visits getVisits(int index)
    {
        //Return the visit object at the <index> place in the list

        int count = 0;
        foreach (Visits vis in visits)
        {
            //Go through all the visit objects
            if (index == count)
                //If we're at the correct point in the list...
                return vis;
            //exit this method and return the current visit
            count++;
            //Keep counting
        }
        return null;
        //Return null if an index was entered that could not be found
    }
}

} }

then the code to add 然后添加代码

            thePickup.name = txtCustName.Text;
            thePickup.address = txtCustAddress.Text;
            thePickup.arrival = DateTime.Parse(txtArrival.Text);
            thePickup.Dname = txtDeliveryName.Text;
            thePickup.Daddress = txtDaddress.Text;
            thePickup.Lat = Double.Parse(txtLat.Text);
            thePickup.Lon1 = Double.Parse(txtLong.Text);
            thePickup.type = "Pickup";
            //Update thePickup object to reflect any changes made by the user

            XmlSerializer SerializerObj = new XmlSerializer(typeof(Pickups));

        using (TextWriter WriteFileStream = new StreamWriter(@"Pickup.xml", true))
        {
            SerializerObj.Serialize(WriteFileStream, thePickup);
        }

When I add a new entry It just changes the format of the original entry 当我添加新条目时,它只是更改了原始条目的格式

You should try to use XPath supported libraries to handle XML Assembling and creation. 您应该尝试使用XPath支持的库来处理XML汇编和创建。

As you are using C# i would recomend HtmlAgilityPack for handling the "Parsing" thing. 当您使用C#时,我建议使用HtmlAgilityPack处理“解析”问题。

In order to build the XML, here is a good source for learning how to do so using XPath. 为了构建XML, 这里是学习如何使用XPath的好资源。

You can also use the native XMLDocument class from C# with in your case may be more useful if you are building it without any parsing logic before. 您还可以使用C#的本机XMLDocument类,如果您之前没有任何解析逻辑的情况下构建它,则可能会更有用。

Take a look here 在这里看看

XPath Sample: XPath示例:

Here is an XPath sample that would help you to avoid overriding the actual node in the XML File. 这是一个XPath示例,可以帮助您避免覆盖XML文件中的实际节点。

CreateTag("//NODE1/NODE2", "TAG_NAME", tagContent);


    private void CreateTag(string xPath, string tag, string tagContent)
    {
        XmlNode node = _xml.SelectSingleNode(xPath);
        XmlElement element = _xml.CreateElement(tag);

        element.InnerText = tagContent;
        node.AppendChild(element);
    }

In case your set has multiple nodes with the same name : 如果您的集合有多个同名节点:

CreateTag("//SINTEGRA//SEARCH//RECORDS//RECORD[last()]", kv.Key, kv.Value);

Where last() is a XPath method that is implemented by most of .dlls that returns the index to the lastnode + 1 so that your node will be inserted after the last created one 其中last()是由大多数.dll实现的XPath方法,该方法将索引返回到lastnode + 1,以便在最后一个创建的节点之后插入您的节点

Try this: 尝试这个:

using(TextWriter WriteFileStream = new StreamWriter(@"Pickups.xml", true))
{
    SerializerObj.Serialize(WriteFileStream, thePickup);
}

instead. 代替。

The boolean true parameter means that the StreamWriter will append the next written block to the existing file, instead of overwriting it boolean true参数表示StreamWriter将下一个写入的块append到现有文件中,而不是覆盖它

Otherwise, your code overwrites Pickups.xml file each time. 否则,您的代码每次都会覆盖Pickups.xml文件。 And don't forget to close WriteFileStream object. 并且不要忘记关闭WriteFileStream对象。

I tried to reproduce your case: 我试图重现您的情况:


    public class Pickups
    {
        public string name { get; set; }
        public string address { get; set; }
        public string Dname { get; set; }
        public string Daddress { get; set; }
        public string type { get; set; }
        public DateTime arrival { get; set; }
        public DateTime Lat { get; set; }
        public DateTime Lon1 { get; set; }
    }

class Program
{


    static void Main()
    {
        Pickups thePickup = new Pickups();
        thePickup.name = "nameProp";
        thePickup.address = "addressProp";
        thePickup.arrival = DateTime.Now;
        thePickup.Dname = "txtDeliveryName";
        thePickup.Daddress = "txtDaddress";
        thePickup.Lat = DateTime.Now;
        thePickup.Lon1 = DateTime.Now;
        thePickup.type = "Pickup";
        //Update thePickup object to reflect any changes made by the user

        XmlSerializer SerializerObj = new XmlSerializer(typeof(Pickups));

        using (TextWriter WriteFileStream = new StreamWriter(@"Pickups.xml", true))
        {
            SerializerObj.Serialize(WriteFileStream, thePickup);
        }

        Pickups thePickup1 = new Pickups();
        thePickup1.name = "nameProp2";
        thePickup1.address = "addressProp2";
        thePickup1.arrival = DateTime.Now;
        thePickup1.Dname = "txtDeliveryName2";
        thePickup1.Daddress = "txtDaddress2";
        thePickup1.Lat = DateTime.Now;
        thePickup1.Lon1 = DateTime.Now;
        thePickup1.type = "Pickup2";

        using (TextWriter WriteFileStream = new StreamWriter(@"Pickups.xml", true))
        {
            SerializerObj.Serialize(WriteFileStream, thePickup1);
        }
    }

}

And in Pickups.xml file I get expected result(2 entities): Pickups.xml文件中,我得到了预期的结果(2个实体):

<?xml version="1.0" encoding="utf-8"?>
<Pickups xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <name>nameProp</name>
  <address>addressProp</address>
  <Dname>txtDeliveryName</Dname>
  <Daddress>txtDaddress</Daddress>
  <type>Pickup</type>
  <arrival>2012-12-05T15:30:37.809487+01:00</arrival>
  <Lat>2012-12-05T15:30:37.810487+01:00</Lat>
  <Lon1>2012-12-05T15:30:37.810487+01:00</Lon1>
</Pickups><?xml version="1.0" encoding="utf-8"?>
<Pickups xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <name>nameProp2</name>
  <address>addressProp2</address>
  <Dname>txtDeliveryName2</Dname>
  <Daddress>txtDaddress2</Daddress>
  <type>Pickup2</type>
  <arrival>2012-12-05T15:30:37.989487+01:00</arrival>
  <Lat>2012-12-05T15:30:37.989487+01:00</Lat>
  <Lon1>2012-12-05T15:30:37.989487+01:00</Lon1>
</Pickups>

Are you sure you fixed all parts of your program? 确定要修复程序的所有部分吗? Maybe you write to the same file from different places in your code? 也许您从代码中的不同位置写入同一文件?

Do not serialize a single element but a list: 不要序列化单个元素,而要序列化:

 List<Pickups> list = new List<Pickups>();

 foreach ( var pickup in ... )
    list.Add( pickup );

 ...
 XmlSerializer SerializerObj = new XmlSerializer(typeof(List<Pickups>));

 TextWriter WriteFileStream = new StreamWriter(@"Pickups.xml");
 SerializerObj.Serialize( WriteFileStream, list );

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

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