2016-10-18 2 views
0

다음은 XML입니다. 오류가 발생한 줄 번호를 기반으로 레코드/행 번호를 가져 오려고합니다. 예를 들어, 유효성 검사 오류 값이 Line 6 인 0.53에서 발생했다면, 여기에 기록 번호 1을 알고 싶습니다. id="1", id="2" .. 등을 record에 추가하는 것은 좋은 선택이 될 수 있지만 필자의 요구 사항에 따라 XML 형식은 변경 될 수 있습니다. 오류 줄 번호를 기반으로 XML 레코드 번호를 가져옵니다. C#

<?xml version='1.0' encoding='utf-8'?> 
<records> 
    <record> 
    <date>2016-02-01</date> 
    <id>3</id> 
    <value>0.53</value> 
    <unit>mtrs</unit> 
    </record> 
    <record> 
    <date>2016-02-01</date> 
    <id>4</id> 
    <value>0.13</value> 
    <unit>mtrs</unit> 
    </record> 
    <record> 
    <date>2016-02-01</date> 
    <id>7</id> 
    <value>0.13</value> 
    <unit>mtrs</unit> 
    </record> 
</records> 

다음

나는 다음과 같은 접근 방식을 시도 IXmlLineInfo

 //get the input file here 
     var httpRequest = HttpContext.Current.Request; 

     if (httpRequest.Files.Count > 0) 
     { 
      var postedFile = httpRequest.Files[0]; 

      //sete the xsd schema path      
      string xsdPath = HttpContext.Current.Server.MapPath("~/XSD/MyFile.xsd"); 

      //set the XSD schema here 
      var schema = new XmlSchemaSet(); 
      schema.Add("", xsdPath); 
      var Message = ""; 

      //validate the xml schema here 
      XDocument document = XDocument.Load(postedFile.InputStream, LoadOptions.PreserveWhitespace | LoadOptions.SetLineInfo | LoadOptions.SetBaseUri); 
      //create a lists to add the error records 
      List<string> lstErrors = new List<string>(); 
      document.Validate(schema, ValidationEventHandler); 

      //validate all the errors 
      document.Validate(schema, (sender, args) => 
      { 
       IXmlLineInfo item = sender as IXmlLineInfo; 
       if (item != null && item.HasLineInfo()) 
       { 
        //capture all the details needed here seperated by colons 
        Message = item.LineNumber + ";" + 
        (((System.Xml.Linq.XObject)item).Parent.Element("id")).Value + ";" + 
        ((System.Xml.Linq.XElement)item).Name.LocalName + ";" + 
        args.Message + Environment.NewLine; 
        //add the error to a list 
        lstErrors.Add(Message); 
       } 
      }); 
     } 

답변

1

를 사용하여 오류 줄 정보를 얻고, 내 코드입니다.

유효성 검사를하기 전에 문서로드 후 각 record 요소에 대한 색인 및 ID에 대한 정보가 들어있는 사전을 만듭니다.

XDocument document = XDocument.Load(...); 

var dict = document.Root.Elements("record") 
    .Select((r, index) => new { r, index }) 
    .ToDictionary(a => a.r, a => a.index); 

그런 다음 유효성 검사 이벤트에서이 사전을 사용

if (item != null && item.HasLineInfo()) 
{ 
    Message = dict[((XObject)item).Parent] + ";" + 
     item.LineNumber + ";" + 
     (((XObject)item).Parent.Element("id")).Value + ";" + 
     ((XElement)item).Name.LocalName + ";" + 
     args.Message + Environment.NewLine; 

    lstErrors.Add(Message); 
} 
+0

작은 문제는 내가 확인하기 전에 사전에 값을 추가하면 가능성이 비 고유 ID 값이하려고하는 것이있다,있다 들어가서 예외를 던집니다. 유효성 검사 이벤트 도중 또는 후에이 메서드를 구현할 수있는 방법이 있습니까? – Srini

+1

@Srini - 업데이트를 참조하십시오. 우리는 뭔가 특별한 것이 필요합니다. 요소에 대한 참조를 사용하기로 결정했습니다. –

관련 문제