XML文档不能包含多个根级元素

本文关键字:元素 包含多 文档 不能 XML | 更新日期: 2023-09-27 18:14:48

我有一个代码列表,其中有一个错误"XML文档不能包含多个根级元素">

<Employee>
  <Name ID= "JanRich">Janice Richardson</Name>
  <Role>Finance Supervisor</Role>
  <Department>Sales</Department>
  <CPF_Number>370-16-3631</CPF_Number>
  <Marital_Status>Single</Marital_Status>
  <Salary>$4,500</Salary>
</Employee>
<Employee>
  <Name ID= 'AlanWu'>Alan Wu</Name>
  <Role></Role>
  <Department>Research</Department>
  <CPF_Number>
    385-22-3311
  </CPF_Number>
  <Marital_status>Married</Marital_status>
  <Salary>$52,800</Salary>
</Employee>

错误发生在第一个<Employee>标记处。

XML文档不能包含多个根级元素

XML文档must有一个并且只有一个根元素。您必须添加根元素。例如,

<?xml version="1.0" encoding="utf-8" ?> 
<Employees>
    <Employee>
       .....
    </Employee>
    <Employee>
       ....
    </Employee>
</Employees>

假设您无论如何都要打开文档,则可以将XmlReaderConformanceLevel设置为ConformanceLevel.Fragment

XmlReaderSettings settings = new XmlReaderSettings();
settings.ConformanceLevel = ConformanceLevel.Fragment;
// input is a stream or filename
using (XmlReader reader = XmlReader.Create(input, settings)) {
    // use the reader
}

您只需添加根元素即可解决错误。。。。。。。

 <root>
    <Employee>   
      <Name ID= "JanRich">Janice Richardson</Name>   <Role>Finance Supervisor</Role>   
      <Department>Sales</Department>   <CPF_Number>370-16-3631</CPF_Number>     
      <Marital_Status>Single</Marital_Status>   <Salary>$4,500</Salary> 
    </Employee> 
   <Employee>   <Name ID= 'AlanWu'>Alan Wu</Name>   <Role></Role>        
     <Department>Research</Department>   <CPF_Number>     385-22-3311     
     </CPF_Number>        
     <Marital_status>Married</Marital_status>   <Salary>$52,800</Salary> 
   </Employee> 
 </root>
<?xml version="1.0" encoding="utf-8"?>
<ArrayOfTestClass>
  <testClass>
    <a>attr1</a>
  </testClass>
  <testClass>
    <a>attr2</a>
  </testClass>
</ArrayOfTestClass>

像这个