C# 没有Unicode字节顺序标记。无法切换到Unicode
我正在用XSD编写一个XML验证程序 下面是我所做的,但是当验证器到达行C# 没有Unicode字节顺序标记。无法切换到Unicode,c#,xml,character-encoding,xsd,xmlreader,C#,Xml,Character Encoding,Xsd,Xmlreader,我正在用XSD编写一个XML验证程序 下面是我所做的,但是当验证器到达行while(list.Read())时,它给出了错误 没有Unicode字节顺序标记。无法切换到Unicode 谁能帮我修一下吗 public class Validator { public void Validate(string xmlString) { Boolean bRet = true; string xmlPath = @
while(list.Read())
时,它给出了错误
没有Unicode字节顺序标记。无法切换到Unicode
谁能帮我修一下吗
public class Validator
{
public void Validate(string xmlString)
{
Boolean bRet = true;
string xmlPath = @"C:\x.xml";
string xsdPath = @"C:\general.xsd";
XmlReaderSettings Settings = new XmlReaderSettings();
Settings.Schemas.Add("", xsdPath);
Settings.ValidationType = ValidationType.Schema;
Settings.ValidationEventHandler +=
new ValidationEventHandler(SettingsValidationEventHandler);
XmlReader list = XmlReader.Create(xmlPath, Settings);
//StringBuilder output = new StringBuilder();
while (list.Read())
{
}
//File.WriteAllText(@"D:\Output.xml", output.ToString());
}
static void SettingsValidationEventHandler(object sender,
ValidationEventArgs e)
{
if (e.Severity == XmlSeverityType.Warning)
{
MessageBox.Show( "WARNING: ");
MessageBox.Show(e.Message);
}
else if (e.Severity == XmlSeverityType.Error)
{
MessageBox.Show("ERROR: ");
MessageBox.Show(e.Message);
}
}
}
XML
XSD
文件编码的实际情况似乎与XML声明指定的编码冲突。例如,如果文件实际使用单字节字符,则声明
encoding=“utf-16”
不会将其更改为使用双字节字符
尝试从XML声明中删除冲突的编码。替换
<?xml version="1.0" encoding="utf-16"?>
与
您还可以使用LoadXML()将文件加载到字符串中作为变通方法。如果您无法将xml文件编码更改为
<?xml version="1.0"?>
如果使用XmlDocument
var xmlDoc = new XmlDocument();
xmlDoc.LoadXml(File.ReadAllText(filePath));
您确定“物理”文件x.xml的编码正确吗?使用Sublime或jEdit等文本编辑器打开它,检查实际编码。是的,我在服务器端使用同一xsd文件中生成的c#类创建了此XML文件,并且格式良好。这段代码在客户端,我只想在客户端用相同的xsd验证我收到的xml文件。
可能也可以。是的,因为utf-8
是默认编码。在遇到类似错误后,这个答案帮助我解决了自己的问题。在我的例子中,我首先以编程方式创建xml,然后在稍后对其进行读写。如果要使用xmlwriter
删除/更改处理指令中的编码版本,请使用writer.WriteProcessingInstruction(“xml”,“version='1.0')
(其中writer
是XmlWriter
的一个实例)。请参阅变通方法“您也可以使用LoadXML()将文件加载到字符串中作为变通方法。”这对我很有用。不要使用file.ReadAllText
。始终创建StreamReader
和FileStream
。永远不要在内存中分配文件大小的块。@Mr.TA,如果它是已知的小文件,如设置或任何文件。ReadAllText完全可以。
<?xml version="1.0"?>
<?xml version="1.0"?>
XmlReader.Create(new StringReader(File.ReadAllText(fileName)));
var xmlDoc = new XmlDocument();
xmlDoc.LoadXml(File.ReadAllText(filePath));