是否可以将存储在HttpPostedFileBase属性中的xml文件(来自MVC格式),并创建一个XMLReader.Create(..,..)对象,维护行号?
以下示例使用硬编码的xml文件位置..
理想情况下是XmlReader.Create(MyHttpPostedFileBase,rs);
public static bool Validate()
{
try
{
string XsdPath = @"C:\Projects\Mvc\Xsd\books.xsd";
string XmlPath = @"C:\Projects\Mvc\Xsd\food.xml"; //replace with my HttpPostedFileBase
XmlSchemaSet set = new XmlSchemaSet();
set.Add(null, XsdPath);
XmlReaderSettings rs = new XmlReaderSettings();
rs.Schemas = set;
rs.ValidationType = ValidationType.Schema;
rs.ValidationEventHandler += new ValidationEventHandler(rs_ValidationEventHandler);
using (XmlReader reader = XmlReader.Create(XmlPath, rs))
{
while (reader.Read()) ;
}
}
static void rs_ValidationEventHandler(object sender, ValidationEventArgs e)
{
//code
}
答案 0 :(得分:1)
管理以找出解决方案 - 希望这会有助于其他人。
从HttpPostedFileBase Xml上载创建XmlDocument的问题是XmlDocument组件不维护行号。
解决方案是从HttpPostedFileBase创建一个流并将其插入到XmlReader.Create()中。
下面的代码做了两件事:验证XML是有效的,然后验证XML而不是XSD。
注意:我还没有时间重构代码,但它应该是可以理解的
public HttpPostedFileBase MyFile { get; set; }
public Stream GetXmlStream()
{
using (Stream inputStream = MyFile.InputStream)
{
MemoryStream memoryStream = inputStream as MemoryStream;
memoryStream = new MemoryStream();
inputStream.CopyTo(memoryStream);
memoryStream.Position = 0;
return memoryStream;
}
}
public class XmlValidator
{
public string Error;
public bool ValidateXml(Stream memoryStream)
{
try
{
string XsdPath = @"C:\Projects\Mvc\Xsd\books.xsd";
XmlReaderSettings settings = new XmlReaderSettings();
settings.Schemas.Add("", XsdPath);
settings.ValidationType = ValidationType.Schema;
XmlReader reader = XmlReader.Create(memoryStream, settings);
XmlDocument document = new XmlDocument();
try
{
document.Load(reader);
}
catch (XmlException ex)
{
UploadedFile.Error = String.Format("Line {0}, position {1}: {2}", ex.LineNumber, ex.LinePosition,
ex.Message);
return false;
}
ValidationEventHandler eventHandler = new ValidationEventHandler(ValidationEventHandler);
document.Validate(eventHandler);
reader.Close();
return true;
}
catch (XmlSchemaValidationException ex)
{
UploadedFile.Error = String.Format("Line {0}, position {1}: {2}", ex.LineNumber, ex.LinePosition, ex.Message);
}
return false;
}
private void ValidationEventHandler(object sender, ValidationEventArgs e)
{
}
}