如何使用c#在xml文件中存储更多根

时间:2014-03-17 13:57:44

标签: c# xml

我创建了一个xml文件名是这个xml文件中的data.xml我正在存储这些信息   像贝娄一样

<products>
  <cloths Id="1">
    <ClothName>Sharts</ClothName>
    <Size>40</Size>
    <Price>1050</Price>
    <Amount>1000000</Amount>
    <images>c:\users\venkateshg\documents\visual studio 2010\Projects\WebApplication1\WebApplication1\ImgUpload\Tulips.jpg</images>
  </cloths>
</products>

这是我开发的C#代码

 XmlDocument XDoc = new XmlDocument(); // root
 XmlElement XElemRoot = XDoc.CreateElement("products");
 XDoc.AppendChild(XElemRoot);
 XmlElement XCloths = XDoc.CreateElement("cloths");
 DataSet ds = new DataSet();
 ds.ReadXml(Server.MapPath("data.xml"));
 int idval  ;
 if (ds.Tables[0].Rows.Count > 1)
 {
    idval = ds.Tables[0].Columns[5][0];
    if (idval == 0)
    {
       idval = 1;
    }
    else
    {
       idval += 1;
    }
 }
 else
 {
    idval = 1;
 }
 XCloths.SetAttribute("Id",idval.ToString());
 XElemRoot.AppendChild(XCloths);
 XmlElement XClothName = XDoc.CreateElement("ClothName");
 XClothName.InnerText = TextBox1.Text;
 XCloths.AppendChild(XClothName);
 XmlElement XSize = XDoc.CreateElement("Size");
 XSize.InnerText = TextBox2.Text; ;
 XCloths.AppendChild(XSize);
 XmlElement XPrice = XDoc.CreateElement("Price");
 XPrice.InnerText = TextBox3.Text;
 XCloths.AppendChild(XPrice);
 XmlElement XAmount = XDoc.CreateElement("Amount");
 XAmount.InnerText = "1000000";
 XCloths.AppendChild(XAmount);
 FileUpload1.ToolTip = "Select Image For Upload...";
 string ext = System.IO.Path.GetExtension(this.FileUpload1.PostedFile.FileName);
 if (FileUpload1.HasFile)
 {
    //Check File is available in Fileupload control and then upload to server path
    string fname = FileUpload1.FileName;
    //spath = @"~\ImgUpload\" + FileUpload.FileName;
    string fpath = Server.MapPath("ImgUpload");
    fpath = fpath + @"\" + FileUpload1.FileName;
    string getext = System.IO.Path.GetExtension(FileUpload1.PostedFile.FileName);
    string filename = System.IO.Path.GetFileNameWithoutExtension(FileUpload1.PostedFile.FileName);
    string strFilePath = filename + DateTime.Now.ToString("yyyyMMdd") + getext;
    if (getext != ".JPEG" && getext != ".jpeg" && getext != ".JPG" && getext != ".jpg" && getext != ".png" && getext != ".tif" && getext != ".tiff")
    {
       Page.ClientScript.RegisterStartupScript(typeof(Page), "successfull", "alert('Please upload only jpeg, jpg,png,tif,tiff'); window.location = 'Default.aspx';", true);
    }
    else
    {
       FileUpload1.SaveAs(Server.MapPath(@"~\ImgUpload\" + strFilePath));
       Image1.ImageUrl = @"~\ImgUpload\" + strFilePath;
       ViewState["fname"] = fname;
       ViewState["fPath"] = @"~\ImgUpload\" + strFilePath;
       XmlElement Ximages = XDoc.CreateElement("images");
       Ximages.InnerText = fpath;
       XCloths.AppendChild(Ximages);
    }
 }
 else
 {

 }**

问题是如果我每次提交日期都要重新加载相同的ID&#34; 1&#34;

我想继续在一个xml文件中识别1,2,3,4,5 ................

2 个答案:

答案 0 :(得分:1)

除非您对数据集有一些错综复杂的目的,否则我相信您可以完全放弃它。

然后你有以下内容:

XDocument xDoc;
int lastId = 0;

var path = Server.MapPath("data.xml");
if (File.Exists(path))
{
   xDoc = XDocument.Load(path);
   var existingCloths = xDoc.Root.Elements("cloths");
   if (existingCloths.Any())
   {
       lastId = existingCloths.Max(c => Int32.Parse(c.Attribute("Id").Value));
   }
}
else
{
   xDoc = new XDocument(new XElement("products"));
}

var xCloths = XDoc.CreateElement("cloths");
xDoc.Add(new XAttribute("Id",
                        (lastId + 1).ToString(CultureInfo.InvariantCulture));
xDoc.Root.Add(xCloths);

//[...]

答案 1 :(得分:0)

我个人觉得创建一个Class并序列化和反序列化到xml要容易得多。 如果要自定义类,则需要在适当的[XMLRoot] [XMLElement]和[XMLAttribute]标记中添加到Products类

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

namespace UShort
{
class Program
{
    static void Main(string[] args)
    {
        Products prod = new Products();
        prod.Cloths = new List<Products.cloths>();
        Products.cloths jacket = new Products.cloths();

        jacket.ClothName = "MyJacket";
        jacket.amount = 12345;
        jacket.price = (float)123.45;
        jacket.size = 12;
        jacket.images = "c:\\asdasd.jpg";

        prod.Cloths.Add(jacket);
        // String contining XML. Do what you want with it.
        string ProductXML = XMLTools.convertObjToXMLString(prod);   
        // Create an object from an XML string of the same format.
        Products NewProduct = (Products)XMLTools.convertXMLStringToObject(ProductXML, typeof(Products));
    }

    public class Products
    {
        public List<cloths> Cloths = new List<cloths>();
        public class cloths
        {
            public string ClothName = string.Empty;
            public int size = 0;
            public float price = 0;
            public long amount = 0;
            public string images = string.Empty;
        }
    }

    public static class XMLTools
    {
        /// <summary>
        /// Overwrites the encoding to use UTF-8
        /// </summary>
        private class Utf8StringWriter : StringWriter
        {
            public override Encoding Encoding
            {
                get { return Encoding.UTF8; }
            }
        }

        public static string convertObjToXMLString(object obj)
        {
            try
            {
                XmlSerializer serObj = new XmlSerializer(obj.GetType());
                Utf8StringWriter sw = new Utf8StringWriter();
                XmlTextWriter xtw = new XmlTextWriter(sw);
                xtw.Formatting = Formatting.Indented;
                serObj.Serialize(xtw, obj);

                return sw.ToString();
            }
            catch (Exception)
            {
                throw;
            }
        }

        public static object convertXMLStringToObject(string xmlString, Type objectType)
        {
            try
            {
                TextReader txr = new StringReader(xmlString);
                XmlSerializer serObj = new XmlSerializer(objectType);

                return serObj.Deserialize(txr);
            }
            catch (Exception)
            {
                throw;
            }
        }
    }
}

}