C# Xml Load Error) System.Xml.XmlException: 'Data at the root level is invalid. Line 1, position 1.'

반응형

 

Error

  • XML 파일 호출시 에러 발생
System.Xml.XmlException: 'Data at the root level is invalid. Line 1, position 1.'

 

  • 에러가 발생한 축약 코드
// XML 파일을 불러올 경로와 파일 이름
string filePath = "C:\\example\\data.xml";

// XmlDocument 객체 생성
XmlDocument xmlDoc = new XmlDocument();

// XML 파일 불러오기
xmlDoc.LoadXml(filePath);

해결 방법

  • XML 파일을 불러 올 때 LoadXml이 아닌 Load 함수로 호출
  • Load 함수로 호출한 XML 파일 읽기 코드
// XML 파일을 불러올 경로와 파일 이름
string filePath = "C:\\example\\data.xml";

// XmlDocument 객체 생성
XmlDocument xmlDoc = new XmlDocument();

// XML 파일 불러오기
xmlDoc.Load(filePath);

작동 확인

  • xml 파일과 hml 파일을 불러오는 다이얼로그를 출력하고 해당 문서의 내용을 확인하기
// XML 파일을 불러올 경로와 파일 이름, 전역 변수로 선언
//String filePath;

// 파일 선택 다이얼로그
OpenFileDialog fileDialog = new OpenFileDialog();
fileDialog.Filter = "xml 문서 파일|*.xml|hml 문서 파일|*.hml|모든 파일|*.*";
if (fileDialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
    // 선택한 파일의 경로 저장
    filePath = fileDialog.FileName;
    MessageBox.Show(filePath);
}

// XmlDocument 객체 생성
XmlDocument xmlDocument = new XmlDocument();

// XML 파일 불러오기
xmlDocument.Load(filePath);

// XML 파일의 루트 요소 가져오기
XmlElement root = xmlDocument.DocumentElement;

// 루트 요소의 하위 요소들 가져오기
XmlNodeList nodes = root.ChildNodes;

// 하위 요소들의 값 출력
foreach (XmlNode node in nodes)
{
    MessageBox.Show(node.InnerText);
}

 

  • 테스트를 위한 xml 문서
<!-- xml base test.xml -->
<root>
  <test>
    <content> Hello World</content>
  </test>
</root>

 

  • 실행

반응형