문제

나는 받고있다 NullReferenceException XML-File의 속성을 읽으려고 할 때-사용자 입력에 의해 정의되는 요소에서 읽을 속성.

스택 트레이스는이 라인으로 나를 계속 리디렉션합니다 (표시)

XmlDocument _XmlDoc = new XmlDocument();
_XmlDoc.Load(_WorkingDir + "Session.xml");
XmlElement _XmlRoot = _XmlDoc.DocumentElement;
XmlNode _Node = _XmlRoot.SelectSingleNode(@"group[@name='" + _Arguments[0] + "']");
XmlAttribute _Attribute = _Node.Attributes[_Arguments[1]]; // NullReferenceException

요점을 어디서 놓쳤습니까? 여기서 어떤 참조가 누락 되었습니까? 나는 그것을 알아낼 수 없다 ...

편집 : 요소가 존재하며 속성도 있습니다 (값 포함)

<?xml version="1.0" encoding="utf-8"?>
<session>
 <group name="test1" read="127936" write="98386" />
 <group name="test2" read="352" write="-52" />
 <group name="test3" read="73" write="24" />
 <group name="test4" read="264524" write="646243" />
</session>

추가 설명 : _Arguments[] 사용자 입력의 분할 배열입니다. 사용자 예를 들어 입력 test1_read - 그것은 나뉘어진다 _Arguments[0] = "test" 그리고 _Arguments[1] = "read"

도움이 되었습니까?

해결책

당신은 더 나은 것을 사용하지 않겠습니까? xmlelement.getAttribute 방법? 이것은 당신이 그것을 사용할 수 있음을 의미합니다 xmlelement.hasattribute 액세스하기 전에 수표를 작성합니다. 이것은 확실히 NullReference를 피할 것입니다.

견본

XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load(_WorkingDir + "Session.xml");
XmlElement xmlRoot = xmlDoc.DocumentElement;
foreach(XmlElement e in xmlRoot.GetElementsByTagName("group"))
{
    // this ensures you are safe to try retrieve the attribute
    if (e.HasAttribute("name")
    { 
        // write out the value of the attribute
        Console.WriteLine(e.GetAttribute("name"));

        // or if you need the specific attribute object
        // you can do it this way
        XmlAttribute attr = e.Attributes["name"];       
        Console.WriteLine(attr.Value);    
    }
}

또한 사용을 살펴 보는 것이 좋습니다. linqtoxml .NET에서 XML 문서를 구문 분석 할 때.

다른 팁

XML 파일이 없으면 구문 분석하는 경우 XPath 표현식에서 지정해야한다고 생각합니다. //group 간단한 대신 group.

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