如何在xml

时间:2016-05-19 11:31:04

标签: c# xml

我正在创建XML来发送数据。数据包含多种数据类型,如字符串,整数和小数。我的XML格式和c#代码创建如下。

<root>   
  <data>     
    <struct>        
      <PartnerCD></PartnerCD>         
      <UserName> </UserName>        
      <Password> </Password>      
      <Action> </Action>        
      <OfficeCD></OfficeCD>        
      <ChannelCD></ChannelCD>      
      <Token></Token>       
      <Notes> </Notes>        
      <Products>         
        <Product>
          <ProductID></ProductID>
          <SVA></SVA>
          <Amount></Amount>
        </Product>                
     </Products>      
   </struct>   
  </data> 
</root>

我的c#代码是

 public static string CreateRequestXML(string partnerCd, string userName, string password, string action, string productId, string token, string sva, string amount)
    {
        XmlDocument doc = new XmlDocument();

        XmlElement elemRoot = doc.CreateElement("root");
        XmlElement elemData = doc.CreateElement("data");
        XmlElement elemStruct = doc.CreateElement("struct");
        XmlElement elemProducts = doc.CreateElement("Products");
        XmlElement elemProduct = doc.CreateElement("Product");

        doc.AppendChild(elemRoot);
        elemRoot.AppendChild(elemData);
        elemData.AppendChild(elemStruct);
        //Insert data here
        InsertDataNode(doc, elemStruct, "PartnerCD", partnerCd);
        InsertDataNode(doc, elemStruct, "UserName", userName);
        InsertDataNode(doc, elemStruct, "Password", password);
        InsertDataNode(doc, elemStruct, "Action", action);
        InsertDataNode(doc, elemStruct, "Token", token);
        elemStruct.AppendChild(elemProducts);
        elemProducts.AppendChild(elemProduct);
        InsertDataNode(doc, elemProduct, "ProductID", productId);
        InsertDataNode(doc, elemProduct, "SVA", sva);
        InsertDataNode(doc, elemProduct, "Amount", amount);

        return doc.OuterXml;
    }

    private static void InsertDataNode(XmlDocument doc, XmlElement parentElem, string nodeName, string nodeValue)
    {
        XmlElement elem = doc.CreateElement(nodeName);
        elem.InnerText = nodeValue;
        parentElem.AppendChild(elem);
    }

我的结果是

<root>
  <data>
    <struct>
      <PartnerCD>123</PartnerCD>
      <UserName>api</UserName>
      <Password>pass</Password>
      <Action>token</Action>
      <Token>4847898</Token>
      <Products>
        <Product>
          <ProductID>123</ProductID>
          <SVA>e8a8227c-bba3-4f32-a2cd-15e8f246344b</SVA>
          <Amount>700</Amount>
        </Product>
      </Products>
    </struct>
  </data>
</root>

我希望PartnerCD和ProductId元素为整数,Amount元素为decimal。我尝试过XMLNodeType但没有用。

3 个答案:

答案 0 :(得分:1)

Xml没有&#34;数据类型的概念&#34;本地,您引用的XmlNodeType是什么类型的 Node (例如元素,属性等),而不是其中包含的数据类型。

答案 1 :(得分:1)

数据类型在XML中是无关紧要的,它都是在它使用的模式中定义的,这是存储预期数据类型声明的地方。

因此,如果您的XSD表明/root/data/struct/PartnerCD的类型为xs:int,则验证文件时会出现验证错误。 XML本身只是所有数据的容器,它不包含元信息。您可以手动定义它,但Point在大约99.99%的情况下超出了我的范围,而且它或多或少是XML的混蛋,比如MSXML,它将了解您的目标。

答案 2 :(得分:1)

就个人而言,我会创建一个对象并将序列化\反序列化为\来自XML,如此......

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

namespace _37321906
{
    class Program
    {
        static void Main(string[] args)
        {
            Root root = new Root();
            root.Data.Struct.PartnerCD = 123;
            root.Data.Struct.UserName = "api";
            root.Data.Struct.Password = "pass";
            root.Data.Struct.Action = "token";
            root.Data.Struct.Token = 4847898;
            root.Data.Struct.Products.Product.Add(new Product { ProductID = 123, SVA = "e8a8227c-bba3-4f32-a2cd-15e8f246344b", Amount = 700.0001 });

            // Serialize the root object to XML
            Serialize<Root>(root);

            // Deserialize from XML
            Root DeserializeRoot = Deserialize<Root>();
        }

        private static void Serialize<T>(T data)
        {

            // Use a file stream here.
            using (TextWriter WriteFileStream = new StreamWriter("test.xml"))
            {
                // Construct a SoapFormatter and use it  
                // to serialize the data to the stream.
                XmlSerializer SerializerObj = new XmlSerializer(typeof(T));

                try
                {
                    // Serialize EmployeeList to the file stream
                    SerializerObj.Serialize(WriteFileStream, data);
                }
                catch (Exception ex)
                {
                    Console.WriteLine(string.Format("Failed to serialize. Reason: {0}", ex.Message));
                }
            }
        }

        private static T Deserialize<T>() where T : new()
        {
            //List<Employee> EmployeeList2 = new List<Employee>();
            // Create an instance of T
            T ReturnListOfT = CreateInstance<T>();


            // Create a new file stream for reading the XML file
            using (FileStream ReadFileStream = new FileStream("test.xml", FileMode.Open, FileAccess.Read, FileShare.Read))
            {
                // Construct a XmlSerializer and use it  
                // to serialize the data from the stream.
                XmlSerializer SerializerObj = new XmlSerializer(typeof(T));
                try
                {
                    // Deserialize the hashtable from the file
                    ReturnListOfT = (T)SerializerObj.Deserialize(ReadFileStream);
                }
                catch (Exception ex)
                {
                    Console.WriteLine(string.Format("Failed to serialize. Reason: {0}", ex.Message));
                }

            }
            // return the Deserialized data.
            return ReturnListOfT;
        }

        // function to create instance of T
        public static T CreateInstance<T>() where T : new()
        {
            return (T)Activator.CreateInstance(typeof(T));
        }
    }

    [XmlRoot(ElementName = "Product")]
    public class Product
    {
        [XmlElement(ElementName = "ProductID")]
        public int ProductID { get; set; }
        [XmlElement(ElementName = "SVA")]
        public string SVA { get; set; }
        [XmlElement(ElementName = "Amount")]
        public double Amount { get; set; }
    }

    [XmlRoot(ElementName = "Products")]
    public class Products
    {
        public Products()
        {
            this.Product = new List<Product>();
        }
        [XmlElement(ElementName = "Product")]
        public List<Product> Product { get; set; }
    }

    [XmlRoot(ElementName = "struct")]
    public class Struct
    {
        public Struct()
        {
            this.Products = new Products();
        }
        [XmlElement(ElementName = "PartnerCD")]
        public int PartnerCD { get; set; }
        [XmlElement(ElementName = "UserName")]
        public string UserName { get; set; }
        [XmlElement(ElementName = "Password")]
        public string Password { get; set; }
        [XmlElement(ElementName = "Action")]
        public string Action { get; set; }
        [XmlElement(ElementName = "OfficeCD")]
        public string OfficeCD { get; set; }
        [XmlElement(ElementName = "ChannelCD")]
        public string ChannelCD { get; set; }
        [XmlElement(ElementName = "Token")]
        public int Token { get; set; }
        [XmlElement(ElementName = "Notes")]
        public string Notes { get; set; }
        [XmlElement(ElementName = "Products")]
        public Products Products { get; set; }
    }

    [XmlRoot(ElementName = "data")]
    public class Data
    {
        public Data()
        {
            this.Struct = new Struct();
        }
        [XmlElement(ElementName = "struct")]
        public Struct Struct { get; set; }
    }

    [XmlRoot(ElementName = "root")]
    public class Root
    {
        public Root()
        {
            this.Data = new Data();
        }
        [XmlElement(ElementName = "data")]
        public Data Data { get; set; }
    }
}

在名为test.xml的构建文件夹中找到您的XML