문제

System.xml.xmlreader의 현재 줄 번호를 얻을 수있는 방법을 아는 사람이 있습니까? 파일에서 XML 요소를 찾는 위치를 기록하려고합니다.

도움이 되었습니까?

해결책

활용하십시오 IXmlLineInfo 인터페이스가 지원합니다 XmlReader:

IXmlLineInfo xmlInfo = (IXmlLineInfo)reader;
int lineNumber = xmlInfo.LineNumber;

다른 팁

확장 IXmlLineInfo 인터페이스, 이것에 대한 문서는 꽤 나쁘다. 약간의 파기를하면 다음을 알려줄 수 있습니다.

1) System.Xml.XmlReader 추상적이므로, 당신은 이것의 사례를 다루지 않을 것입니다. IXmlLineInfo 크게 관련이 없습니다 (그렇지 않으면 모든 것이 조금 더 쉬워 질 것입니다 :))

2) System.Xml.IXmlLineInfo 인터페이스는 두 가지 속성을 제공합니다. LineNumber 그리고 LinePosition (우리가 관심있는 것)와 방법 : HasLineInfo() 문서에 따르면, 구현자가 LineInfo를 반환 할 수 있는지 알려줄 것입니다.

3) 문서화 된 상속자 System.Xml.XmlReader, 우리는 다음과 같습니다.

System.Xml.XmlDictionaryReader - abstract, used by WCF for serialization, no IXmlLineInfo
System.Xml.XmlNodeReader - used when reading a node, no IXmlLineInfo
System.Xml.XmlTextReader - used when reading a stream of data, has IXmlLineInfo
System.Xml.XmlValidatingReader - used when reading a stream of data and validating, has IXmlLineInfo.

위 목록을보고 있습니다 XmlDictionaryReader 내부적으로 사용될 것입니다 XmlNodeReader 노드를 통과하여 읽을 때 사용될 것입니다 (구문 분석 된 상태에서 이미 소스 문서에서 구분되어 있음), XmlTextReader 그리고 XmlValidtingReader (둘 다 구현 IXmlLineInfo), 문서를 읽을 때 사용됩니다. 따라서 길고 부족한 점은 위치 정보를 제공하는 것이 가능하거나 유용하다면 프레임 워크가 그렇게 할 것입니다.

즉, 문서는 매우 가벼운 것 같습니다. 방금이 작업을 수행 한 후, 나는 결국 (_XR이 알려지지 않은 콘크리트 구현이기 때문에 System.Xml.XmlReader):

string position = "(unknown)";
    if (_xr != null && typeof(System.Xml.IXmlLineInfo).IsInstanceOfType(_xr) &&
((System.Xml.IXmlLineInfo)_xr).HasLineInfo())
    {
        System.Xml.IXmlLineInfo li = (System.Xml.IXmlLineInfo)_xr;
        position = "(" + li.LineNumber.ToString() + "," + li.LinePosition.ToString() + ")";
    }

그 모든 것이 말하면서, 실제로 위의 코드를 실행할 때 _xr의 유형은 System.Xml.XsdValidatingReader (그에 대한 문서를 찾는 행운을 빕니다!) System.Xml.XmlReader,하지만 상속하지 않습니다 System.Xml.XmlValidatingReader 또는 System.Xml.XmlTextReader. 따라서 위와 같은 접근 방식을 사용하는 것이 현명 할 것입니다.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top