我有下一个用于XML的序列化类的代码:
public void TestActionPost(Dictionary<string, int> myDictionary)
{
List<DataItem> tempdataitems = new List<DataItem>();
if (myDictionary != null)
{
foreach (string key in myDictionary.Keys)
{
tempdataitems.Add(new DataItem(key, myDictionary[key]));
}
}
XmlWriterSettings settings = new XmlWriterSettings();
settings.OmitXmlDeclaration = true;
settings.NewLineHandling = NewLineHandling.None;
settings.Indent = false;
XmlSerializer serializer = new XmlSerializer(typeof(List<DataItem>));
StringWriter sw = new StringWriter();
XmlWriter writer = XmlWriter.Create(sw, settings);
XmlSerializerNamespaces namespaces = new XmlSerializerNamespaces();
namespaces.Add(string.Empty, string.Empty);
serializer.Serialize(sw, tempdataitems, namespaces);
string xml = sw.ToString();
}
我得到下一个XML字符串输出:
<?xml version=\"1.0\" encoding=\"utf-16\"?>\r\n<ArrayOfDataItem>\r\n <DataItem>\r\n <ApplicationItemId>4929</ApplicationItemId>\r\n <OrderNumber>0</OrderNumber>\r\n </DataItem>\r\n <DataItem>\r\n <ApplicationItemId>1469407</ApplicationItemId>\r\n <OrderNumber>1</OrderNumber>\r\n </DataItem>\r\n</ArrayOfDataItem>
然后我想将此xml传递给存储过程以将数据保存到数据库。但是我的脚本不起作用,因为此字符串在\r\n
字符串中包含\
和<?xml version=\"1.0\" encoding=\"utf-16\"?>
。我尝试手动删除这些字符,它很有效。
如何在没有此字符的情况下获取正常的xml字符串?
P.S。
这是方法调用存储过程并传递我的XML:
public void SaveApplicationItemsOrder(string xml)
{
try
{
using (SqlConnection connection = new SqlConnection(LcciCarnetConnectionString))
{
connection.Open();
SqlCommand command = new SqlCommand("saveApplicationItemsOrder", connection);
command.CommandType = CommandType.StoredProcedure;
SqlParameter parameter = command.Parameters.Add("@xml", SqlDbType.Xml);
parameter.Direction = ParameterDirection.Input;
parameter.Value = xml;
command.Parameters.Add("@rowcount", SqlDbType.Int).Direction = ParameterDirection.Output;
command.ExecuteNonQuery();
}
}
catch (Exception ex)
{
Logger.Log.Error("Application service error", ex);
throw;
}
}
答案 0 :(得分:0)
我解决了这个问题!
我删除了第一个xml(xml声明)<?xml version=\"1.0\" encoding=\"utf-16\"?>
字符串,因为我没有找到解决如何在xml声明中删除/
字符的问题。
通过以下代码删除序列化xml中的所有/r/n
个字符:
public void TestActionPost(Dictionary<string, int> myDictionary)
{
List<DataItem> tempdataitems = new List<DataItem>();
if (myDictionary != null)
{
foreach (string key in myDictionary.Keys)
{
tempdataitems.Add(new DataItem(key, myDictionary[key]));
}
}
XmlWriterSettings settings = new XmlWriterSettings();
settings.OmitXmlDeclaration = true; **//delete xml declaration**
XmlSerializer serializer = new XmlSerializer(typeof(List<DataItem>));
StringWriter sw = new StringWriter();
sw.NewLine = ""; **//delete /r/n**
XmlWriter writer = XmlWriter.Create(sw, settings);
XmlSerializerNamespaces namespaces = new XmlSerializerNamespaces();
namespaces.Add(string.Empty, string.Empty);
serializer.Serialize(writer, tempdataitems, namespaces);
string xml = sw.ToString();
}