나는 내 XML 문서에서 하나의 요소의 값을 선택하는 시간의 악마가 있어요LINQ-To-XML에서 단일 요소를 선택할 수없는 이유는 무엇입니까?
나는 다음을 수행하려고했습니다<?xml version="1.0" encoding="utf-8" ?>
<MySettings>
<AttachmentsPath>Test</AttachmentsPath>
<PendingAttachmentsPath>Test2</PendingAttachmentsPath>
</MySettings>
처럼
내 문서 같습니다
XElement mySettings = XElement.Load("MySettings.xml");
string AttachmentsPath = (from e in mySettings.Descendants("MySettings")
select e.Element("AttachmentsPath")).SingleOrDefault().Value;
또는
XElement mySettings = XElement.Load("MySettings.xml");
string AttachmentsPath = mySettings.Element("AttachmentsPath").Value;
그리고이 작품의 없음. 계속받을 수 있습니다 :
Object reference not set to an instance of an object. Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.NullReferenceException: Object reference not set to an instance of an object.
Source Error:
Line 33:
x => x.Type); Line 34: Line 35:
AttachmentsPath = (from e in mySettings.Descendants("Settings") Line 36:
select e.Element("AttachmentsPath")).SingleOrDefault().Value; Line 37:
XML 문서에 올바르게로드 된 것을 볼 수 있습니다.
내 XML 문서에서이 단일 설정 값에 액세스하려고 할 때 잘못된 것은 무엇입니까? 어떤 방법으로 적절한 방법입니까?
는 null을 반환 할 수 없습니다. 위에서 주어진 XML을 감안할 때. – Godel
@Godel, 요점은 아닙니다.* null을 먼저 검사하지 않고 * SingleOrDefault() *를 호출 한 후에는 속성이나 메서드에 액세스하려고 시도하면 안됩니다. 나쁜 습관 인 모든 코드에서. –
항상 반환해야하는 경우 (null이 아님) Single()을 사용하는 것이 좋습니다. –