gpt4 book ai didi

c# - 读取 XML 时无法转换特殊字符

转载 作者:数据小太阳 更新时间:2023-10-29 02:40:18 25 4
gpt4 key购买 nike

我正在使用以下代码将 XML 导入数据集:

DataSet dataSet = new DataSet();
dataSet.ReadXml(file.FullName);
if (dataSet.Tables.Count > 0) //not empty XML file
{
da.ClearFieldsForInsert();
DataRow order = dataSet.Tables["Orders"].Rows[0];
da.AddStringForInsert("ProductDescription", order["ProductDescription"].ToString());
}

' 这样的特殊字符没有像我认为的那样被翻译成 '

我可以自己在代码中转换它们,但我认为 ReadXML 方法应该自动完成。

这里有什么我遗漏的吗?

编辑:

XML文件相关行:

 <ProductDescription>Grey &apos;Aberdeen&apos; double wardrobe</ProductDescription>

编辑:

然后我尝试使用 XElement:

XDocument doc = XDocument.Load(file.FullName);
XElement order = doc.Root.Elements("Orders").FirstOrDefault();

...

if (order != null)
{
da.ClearFieldsForInsert();
IEnumerable<XElement> items = doc.Root.Elements("Orders");

foreach (XElement item in items)
{
da.ClearFieldsForInsert();
da.AddStringForInsert("ProductDescription", item.Element("ProductDescription").value.ToString());

}

仍然没有转化!

最佳答案

如前所述here , ' 是有效的 XML 转义码。

但是,没有必要在元素值中转义'

<ProductDescription>Grey 'Aberdeen' double wardrobe</ProductDescription>

是有效的 XML。

撇开解决方法不谈,符合标准的 XML 解析器应该尊重预定义的实体,无论它们出现在何处(CDATA 中除外。)

Data.ReadXml 的这种脆弱性和与标准 XML 解析的偏差在文档中注明。我引用:

The DataSet itself only escapes illegal XML characters in XML element names and hence can only consume the same. When legal characters in XML element name are escaped, the element is ignored while processing.


由于其限制,我不会使用 DataTable.ReadXml 进行 XML 解析。相反,您可以使用 XDocument像这样,

using System.Xml.Linq;

...

var doc = XDocument.Load(file.FullName);
var order in doc.Root.Elements("Order").FirstOrDefault();
if (order != null)
{
da.ClearFieldsForInsert();
var productDescription = order.Element("ProductDescription");
da.AddStringForInsert(
"ProductDescription",
productDescription.Value);
}

关于c# - 读取 XML 时无法转换特殊字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28026861/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com