我开发了一个小的 C#
脚本,它可以打开一个 XLS
文件,解析它并创建一个 XML
文件列表来验证它们XSD
文件。
我已尝试将这些经过验证的文件上传到第三方在线服务(为我提供文档/xsd 内容的同一家公司),但一个生成的文件未被接受,因为无效 .
该文件不被接受,因为它在节点属性中的十进制值的开头有一个空格;删除此空格可解决问题。
我创建了一个简单的测试用例,其中 XDocument Validate方法使用额外空间验证 XML 没有任何问题。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Schema;
using System.Xml.Linq;
using System.Xml;
using System.IO;
namespace TestParser {
class Program {
static void Main(string[] args) {
string xsdMarkup =
@"<xs:schema xmlns:xs='http://www.w3.org/2001/XMLSchema'>
<xs:element name='option'>
<xs:complexType>
<xs:simpleContent>
<xs:extension base='xs:string'>
<xs:attribute name='value' type='xs:decimal'>
</xs:attribute>
</xs:extension>
</xs:simpleContent>
</xs:complexType>
</xs:element>
</xs:schema>";
XmlSchemaSet schemas = new XmlSchemaSet();
schemas.Add("", XmlReader.Create(new StringReader(xsdMarkup)));
XDocument doc1 = new XDocument(
new XElement("option","test", new XAttribute("value", " 423423")
));
Console.WriteLine("Validating doc1");
bool errors = false;
doc1.Validate(schemas, (o, e) =>
{
Console.WriteLine("{0}", e.Message);
errors = true;
}, true);
Console.WriteLine("doc1 {0}", errors ? "not valid" : "validated");
Console.WriteLine();
Console.WriteLine("Contents of doc1:");
Console.WriteLine(doc1);
}
}
}
结果是这样的:
Validating doc1
doc1 validated
Contents of doc1:
<option value=" 423423">test</option>
C# XML 解析器验证此 XML 是否正确?
是否可以强制解析器对这种格式更加挑剔?
最佳答案
如果我正确阅读 XML 规范,属性值中的前导空格将被删除(就像 .NET XML 解析器所做的那样):
http://www.w3.org/TR/REC-xml/#AVNormalize
“如果属性类型不是 CDATA,那么 XML 处理器必须通过丢弃任何前导和尾随空格 (#x20) 字符来进一步处理规范化的属性值 [...]”
关于c# - XML 验证 : decimal attribute value starting with a space,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5154297/