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

标签 c# xml

我正在使用以下代码将 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/

相关文章:

php - 将 XML 中的值检索到 PHP 数组中

c# - 单击后按钮上的标签变得模糊,并在 WPF 中恢复动画

c# - 使用 C# 中的 Gdal 库将 shapefile 转换为 kml

c# - 为什么在 C# 8.0 中声明局部函数是静态的

python - 使用 Python 抓取特定页面

c# - 如何使用 C# 读取各个属性值的所有 xml 节点

c# - XDocument XDeclaration 未出现在 ToString 结果中

c# - 从字符串中删除文件类型

c# - 使用服务器端动态创建的 TableRow 的 "onclick"

xml - 使用命名空间时无法复制和修改 XSLT 中的属性