프로그램은 각 XML 파일의 "File"요소 값을 읽고 그것에 대해 작업합니다. 루트 요소가 "CONFIGURATION"인지 먼저 확인하는 if 문이 필요합니다 (프로그램에서 읽고있는 올바른 XML인지 여부를 확인하는 방법입니다). 제 문제는 .Element에 .Any()를 추가 할 수 없다는 것입니다. 그리고 아래의 if 문이 작동하지 않습니다. 변경해야합니다.루트 요소가 있는지 확인하십시오.
if 문 앞에있는 주석을 참조하십시오.
내 코드 : 여기
static void queryData(string xmlFile)
{
var xdoc = XDocument.Load(xmlFile);
var configuration = xdoc.Element("CONFIGURATION");
//The code works except for the if statement that I added.
//The debug shows that configuration is null if no "CONFIGURATION" element is found,
//therefore it prompts a "NullReferenceException" error.
if (configuration == xdoc.Element("CONFIGURATION"))
{
string sizeMB = configuration.Element("SizeMB").Value;
string backupLocation = configuration.Element("BackupLocation").Value;
string[] files = null;
Console.WriteLine("XML: " + xmlFile);
if (configuration.Elements("Files").Any())
{
files = configuration.Element("Files").Elements("File").Select(c => c.Value).ToArray();
}
else if (configuration.Elements("Folder").Any())
{
files = configuration.Elements("Folder").Select(c => c.Value).ToArray();
}
StreamWriter sw = new StreamWriter(serviceStat, true);
sw.WriteLine("Working! XML File: " + xmlFile);
foreach (string file in files)
{
sw.WriteLine(file);
}
sw.Close();
}
else
{
StreamWriter sw = new StreamWriter(serviceStat, true);
sw.WriteLine("XML Configuration invalid: " + xmlFile);
sw.Close();
}
무엇을 :)처럼 뭔가를 할 수있다!? 나는 투표를 무효화하기 위해 뭔가 잘못 했습니까? – Blackator
올바른 XML을 사용하고 있는지 확인하려면 @Blackator와 별도로이 질문을 왜 왜곡 한 적이 있습니까? 그렇다면 XML 스키마가 더 나은 선택 일 것입니다. – Habib