【问题标题】:How to create XML string instead of using string builder?如何创建 XML 字符串而不是使用字符串生成器?
【发布时间】:2011-07-25 01:43:05
【问题描述】:

我正在使用下面的代码(为本示例进行了简化)将数据发布到 SharePoint 列表

StringBuilder customerDoc = new StringBuilder();

customerDoc.Append("<Method ID='1' Cmd='New'>");
customerDoc.Append("<Field Name='Name'>" + Name + "</Field>");
customerDoc.Append("<Field Name='Age'>" + age + "</Field>");
customerDoc.Append("<Field Name='City'>" + city + "</Field>");
customerDoc.Append("<Field Name='Country'>" + country + "</Field>");

customerDoc.Append("</Method>");

XmlDocument xDoc = new XmlDocument();
XmlElement xBatch = xDoc.CreateElement("Batch");
xBatch.SetAttribute("OnError", "Continue");

xBatch.InnerXml = sb_method.ToString();

XmlNode xn_return = sharePoint.listsObj.UpdateListItems(ConfigurationManager.AppSettings["SaveCustomer"].ToString(), xBatch);

如您所见,我使用的字符串生成器并不理想,所以我想知道应该使用什么来创建 XML 字符串?

提前致谢。

【问题讨论】:

  • 您在使用 stringBuilder 时遇到了什么问题?
  • 在创建 xml 文档/字符串时,通常人们似乎对字符串生成器持反对态度。它有效,但我想检查是否可以提高编码标准,但也许我错了
  • 试试 stringwriter 看看这里的区别stackoverflow.com/q/602279/377996
  • 不使用字符串操作的一个简单原因:如果 Name 包含一个 & 符号,该代码将引发异常。

标签: c# asp.net xml sharepoint


【解决方案1】:
    Dim sb As New StringBuilder()
    Dim sb1 As New StringBuilder()
    Dim a As String
    Dim ds As New DataSet()
    sb1.Append("<HEAD ")
    sb1.AppendFormat("invoiceno={0}{1}{0}", Chr(34), invoiceno)
    sb1.AppendFormat(" customercode={0}{1}{0}", Chr(34), Cuscode)
    sb1.AppendFormat(" invDate={0}{1}{0}", Chr(34), invdate)
    sb1.Append(" />")
    a = sb1.ToString()
    sb.Append("<SAVE>")
    For Each dr In dt.Rows
        sb.AppendFormat("<INVOIEC No ={0}{1}{0}", Chr(34), dr("No"), Chr(34))
        sb.AppendFormat(" ItemCode ={0}{1}{0}", Chr(34), dr("ItemCode"), Chr(34))
        sb.AppendFormat(" Qty ={0}{1}{0}", Chr(34), dr("Qty"), Chr(34))
        sb.AppendFormat(" Rate = {0}{1}{0}", Chr(34), dr("Rate"), Chr(34))
        sb.AppendFormat(" Amount = {0}{1}{0}", Chr(34), dr("Amount"), Chr(34))
        sb.AppendFormat(" />")
    Next
    sb.Append("</SAVE>")
    a = sb.ToString()
    Return INVDL.save(sb1, sb, "usp_SaveInvoice")

【讨论】:

  • 通常不鼓励代码转储答案。最好包含简要说明上述代码中发生的事情,以及为什么您决定在创建代码时做出这些设计选择。请记住,您不仅是在回答问题以帮助问题提出者,而且您还在为可能遇到相同问题的未来用户发帖。在你的回答中冗长有很长的路要走。
【解决方案2】:

您可以通过像下面的代码那样分解它来更动态地生成 xml。在这里,我使用 .Add() 方法来附加更多的属性或元素。

兄弟。莫腾

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Dynamic;
using System.Xml.Linq;

namespace Test
{
    class Program
    {
        static void Main(string[] args)
        {
            String name = "Morten";
            Int32 age = 30;
            String city = "Copenhagen";
            String country = "Denmark";

            String customerId = "100";

            XElement xml = new XElement("Method");
            if (!String.IsNullOrEmpty(customerId))
            {
                xml.Add(new XAttribute("ID", 1), new XAttribute("Cmd", "Update"));
            }
            else
            {
                xml.Add(new XAttribute("ID", customerId),new XAttribute("Cmd", "New"));
            }

            xml.Add(
                new XElement("Field", 
                    new XAttribute("Name", "Name"), 
                    name),
                new XElement("Field", 
                    new XAttribute("Name", "Age"), 
                    age),
                new XElement("Field", 
                    new XAttribute("Name", "City"), 
                    city),
                new XElement("Field", 
                    new XAttribute("Name", "Country"), 
                    country)
            );

            Console.WriteLine(xml);
            Console.ReadKey();
        }
    }
}

此代码输出:

<Method ID="1" Cmd="Update">
  <Field Name="Name">Morten</Field>
  <Field Name="Age">30</Field>
  <Field Name="City">Copenhagen</Field>
  <Field Name="Country">Denmark</Field>
</Method>

【讨论】:

    【解决方案3】:
    1. 创建一个模仿您的 XML 架构的类。
    2. 实例化类并填充其属性(属性、元素)
    3. 使用 XmlSerialization 将 XML 片段生成为字符串或流。

    d

    public class Method
    {
      [XmlAttribute()]
      public int ID {get;set;}
    
      [XmlAttribute()]
      public string Cmd {get;set;}
    
      public string Name {get;set;}
      public int Age {get;set;}
      public string City {get;set;}
      public string Country {get;set;}
    }
    
    public class Batch
    {
      public Method Method { get; set; }
    }
    
    public static string ToXml(object Doc)
    {
      try
      {
        // Save to XML string
        XmlSerializer ser = new XmlSerializer(Doc.GetType());
        var sb = new StringBuilder();
        using (var writer = XmlWriter.Create(sb))
        {
          ser.Serialize(writer, Doc);
        }
        return sb.ToString();
      }
      catch (Exception ex)
      { // Weird!
        ProcessException();
      }
    }
    
    var batch = new Batch();
    batch.Method = new Method { ID=..., Cmd=..., ...};
    
    var xml = ToXml(batch);
    

    【讨论】:

      【解决方案4】:

      如果您愿意,您可能希望在项目的这一部分中使用 VB.NET。它允许以非常简洁的方式创建 LINQ to XML 对象:

      Dim xml As XElement = <Method ID="1" Cmd="New">
                                <Field Name="Name"><%= Name %></Field>
                                <Field Name="Age"><%= age %></Field>
                                <Field Name="City"><%= city %></Field>
                                <Field Name="Country"><%= country %></Field>
                            </Method>
      

      【讨论】:

        【解决方案5】:

        如果您已经使用 System.Xml 的 api 创建了 XBatch 元素,为什么不将它用于所有 xml 片段?

            private XmlElement CreateXmlDoc(string name, int age, string city, string country)
            {
                XmlDocument xDoc = new XmlDocument();
                XmlElement xBatch = xDoc.CreateElement("Batch");
                xBatch.SetAttribute("OnError", "Continue");
                xDoc.AppendChild(xBatch);
        
                XmlElement method = xDoc.CreateElement("Method");
                method.SetAttribute("ID", "1");
                method.SetAttribute("Cmd", "New");
                xBatch.AppendChild(method);
        
                method.AppendChild(createFieldElement(xDoc, "Name", name));
                method.AppendChild(createFieldElement(xDoc, "Age", name));
                method.AppendChild(createFieldElement(xDoc, "City", name));
                method.AppendChild(createFieldElement(xDoc, "Country", name));
        
                return xBatch;
            }
        
            private XmlElement createFieldElement(XmlDocument doc, string name, string value) 
            {
                XmlElement field = doc.CreateElement("Field");
                field.SetAttribute("Name", name);
                field.Value = value;
                return field;
            }
        

        【讨论】:

          【解决方案6】:

          您可以使用 Linq to XML,请查看以下内容:http://www.hookedonlinq.com/LINQtoXML5MinuteOverview.ashx

          例如这段代码:

          using System;
          using System.Collections.Generic;
          using System.Linq;
          using System.Text;
          using System.Dynamic;
          using System.Xml.Linq;
          
          namespace Test
          {
              class Program
              {
                  static void Main(string[] args)
                  {
                      String name = "Morten";
                      Int32 age = 30;
                      String city = "Copenhagen";
                      String country = "Denmark";
          
                      XElement xml = new XElement("Method", 
                          new XAttribute("ID", 1), 
                          new XAttribute("Cmd", "New"),
                          new XElement("Field", 
                              new XAttribute("Name", "Name"), 
                              name),
                          new XElement("Field", 
                              new XAttribute("Name", "Age"), 
                              age),
                          new XElement("Field", 
                              new XAttribute("Name", "City"), 
                              city),
                          new XElement("Field", 
                              new XAttribute("Name", "Country"), 
                              country)
                      );
          
                      Console.WriteLine(xml);
                      Console.ReadKey();
                  }
              }
          }
          

          将输出:

          <Method ID="1" Cmd="New">
            <Field Name="Name">Morten</Field>
            <Field Name="Age">30</Field>
            <Field Name="City">Copenhagen</Field>
            <Field Name="Country">Denmark</Field>
          </Method>
          

          【讨论】:

          • 嗨,也许我的例子过于简化了,我实际上有一个条件来检查客户是否已经存在。我怎么能改变你的代码来满足“if (!String.IsNullOrEmpty(customerId)) { sb_method.Append(""); sb_method.Append("" + customerId + ""); } else { sb_method.Append(""); }"
          • 嗨,我不知道如何将我的整个答案和代码放入此评论 - 所以我已将其作为新答案发布在此问题的底部。
          【解决方案7】:

          您应该可以使用System.Xml.XmlDocument。完整的details can be found on MSDN,但它很容易掌握,并且专为编写 XML 文档而设计。

          【讨论】:

            【解决方案8】:

            如果你写xml为什么不使用forward only XmlWriter呢? http://msdn.microsoft.com/en-us/library/system.xml.xmlwriter.aspx 专为创建 xml 结构而设计。

            【讨论】:

              猜你喜欢
              • 2012-09-17
              • 2016-03-25
              • 1970-01-01
              • 2023-01-22
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              相关资源
              最近更新 更多