使用c#加载xml,linq和命名空间

时间:2014-09-29 14:58:43

标签: c# xml

我正在学习一个教程,当我加载一个基本的xml文件时,它工作正常。

XML

<?xml version="1.0" encoding="utf-8" ?>
<Students>
  <Student ID="1">
    <Name>Test1</Name>
  </Student>
  <Student ID="2">
    <Name>Test2</Name>
  </Student>
  <Student ID="3">
    <Name>Test3 </Name>
  </Student>
</Students>

C#

XDocument testXML = XDocument.Load(@"C:\Users\b\Desktop\SITE\xml.xml");
var students = from student in testXML.Descendants("Student")
               select new
               {
                   ID = student.Attribute("ID").Value
               };

foreach (var student in students)
{
    xmlTitle.Text += "</br>" + student.ID + " </br>";

}

输出:

enter image description here

现在,我想在

之前添加此标记
<Students>

<outputTree xmlns="http://www.ibm.com/software/analytics/spss/xml/oms" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.ibm.com/software/analytics/spss/xml/oms http://www.ibm.com/software/analytics/spss/xml/oms/spss-output-1.8.xsd">

我试了很多年但我不能让它运转起来。当我添加

XNamespace ns = "http://www.ibm.com/software/analytics/spss/xml/oms";

1 个答案:

答案 0 :(得分:0)

这对我有用:

XDocument testXML = XDocument.Load(@"C:\Users\b\Desktop\SITE\xml.xml");
var students = from student in testXML.Descendants()
               where student.Name.LocalName == "Student"
               select student;    

foreach (var student in students)
{
    xmlTitle.Text += "</br>" + student.Attribute("ID").Value + " </br>";

}