我有一个来自客户端的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文件。
发布于 2019-05-21 09:29:19
您需要使用非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);
}
}
}https://stackoverflow.com/questions/56231237
复制相似问题