c# - C# 读取使用名称前缀但未在文档本身中定义命名空间的 xml 文件
问题描述
我有一个来自客户端的 xml 文件。它使用带有许多节点的名称前缀。但它没有在文档中定义任何命名空间。下面给出一个示例:
<?xml version="1.0"?>
<SemiconductorTestDataNotification>
<ssdh:DocumentHeader>
<ssdh:DocumentInformation>
<ssdh:Creation>2019-03-16T13:49:23</ssdh:Creation>
</ssdh:DocumentInformation>
</ssdh:DocumentHeader>
<LotReport>
<BALocation>
<dm:ProprietaryLabel>ABCDEF</dm:ProprietaryLabel>
</BALocation>
</LotReport>
</SemiconductorTestDataNotification>
我使用以下 xml 类来读取它但失败了
System.Xml.Linq.XElement
System.Xml.XmlDocument
System.Xml.XmlReader
System.Xml.Linq.XDocument
它给出了错误:
'ssdh' 是一个未声明的前缀。
我知道前缀命名空间。这些将是:
xmlns:ssdh="urn:rosettanet:specification:system:StandardDocumentHeader:xsd:schema:01.13"
xmlns:dm="urn:rosettanet:specification:domain:Manufacturing:xsd:schema:01.14"
自己在 xml 文件中添加这些命名空间是不可行的,因为会有很多 xml 文件,而且这些文件每天都会出现。
是否有可能我创建一个文件(例如 xsd)并在其中写入名称空间并使用 C# 代码中的这个(所谓的)模式文件读取 xml 文件。
解决方案
您需要使用非 xml 方法来读取错误的 xml 文件。尝试以下代码:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Linq;
using System.IO;
namespace ConsoleApplication3
{
class Program1
{
const string BAD_FILENAME = @"c:\temp\test.xml";
const string Fixed_FILENAME = @"c:\temp\test1.xml";
static void Main(string[] args)
{
StreamReader reader = new StreamReader(BAD_FILENAME);
StreamWriter writer = new StreamWriter(Fixed_FILENAME);
string line = "";
while ((line = reader.ReadLine()) != null)
{
if (line == "<SemiconductorTestDataNotification>")
{
line = line.Replace(">",
" xmlns:ssdh=\"urn:rosettanet:specification:system:StandardDocumentHeader:xsd:schema:01.13\"" +
" xmlns:dm=\"urn:rosettanet:specification:domain:Manufacturing:xsd:schema:01.14\"" +
" >");
}
writer.WriteLine(line);
}
reader.Close();
writer.Flush();
writer.Close();
XDocument doc = XDocument.Load(Fixed_FILENAME);
}
}
}
推荐阅读
- r - 如何创建带有基因 ID 的火山图?
- groovy - 使用groovy在xml中获取具有相同节点名称的嵌套xml的值
- database - Maximum recommended children in a Firebase Database node
- php - 当我试图隐藏一个主题时,我的 wordpress 网站上出现了这个内存错误
- tensorflow - CNN 预测
- python - 如何确保变量的值不会在 python 中重置?
- python - pysnmp 陷阱接收器 - 使用异步队列进行处理(无线程)
- php - 如何根据php中的日期和时间计算某些内容是否已过期
- node.js - 电子邮件被 Nodemailer 拒绝发送
- excel - 几列之间的单词查找/映射