首页 > 解决方案 > 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 文件。

标签: c#xmlxml-namespaces

解决方案


您需要使用非 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);
        }
    }

}

推荐阅读