通过c#操作xml

时间:2011-02-14 09:48:11

标签: c# xml linq-to-xml

我有以下xml结构我想通过c#更新它 如何更新它 是否可以通过Linq更新,如果是,那么该怎么做? 我想通过代码添加UnitTest,TestList,TestEntry和UnitTestResults元素。

`

<?xml version="1.0" encoding="UTF-8"?>
<TestRun id="1" xmlns="http://microsoft.com/schemas">
     <TestDefinitions>
    <UnitTest name="Test1" id="T1">
      <Execution id="E1" />   
    </UnitTest>
    <UnitTest name="Test2" id="T2">
      <Execution id="E2" />   
    </UnitTest>
        :
        :

  </TestDefinitions>
    <TestLists>
    <TestList name="List1" id="L1" />
    <TestList name="List2" id="L2" />
     :
      :

  </TestLists>
  <TestEntries>
    <TestEntry testId="T1" executionId="E1" testListId="L1" />
    <TestEntry testId="T2" executionId="E2" testListId="L2" />
    :
    :
  </TestEntries>
  <Results>
    <UnitTestResult executionId="E1" testId="T1" testName="Test1" >
      <Output>
        <ErrorInfo>
          <Message>Hi</Message>
        </ErrorInfo>
      </Output>
    </UnitTestResult>
  </Results>
  <Results>
    :
    :
</TestRun>

`

1 个答案:

答案 0 :(得分:2)

是的,LINQ可以实现。这是添加新UnitTest元素的示例代码:

XDocument doc = XDocument.Load( "tests.xml" );
XNamespace ns = "http://microsoft.com/schemas";

XElement unitTest = new XElement( ns + "UnitTest",
    new XElement( ns + "Execution", new XAttribute( "id", "E3" ) ),
    new XAttribute( "name", "Test3" ),
    new XAttribute( "id", "T3" ) );
doc.Root.Element( ns + "TestDefinitions" ).Add( unitTest );

doc.Save( "tests.xml" );

要添加元素,您必须创建XElement对象,并将新元素的名称及其所有内容(如子元素,属性(通过逗号))传递给其构造函数。然后,您必须指定要添加新元素的位置:从Root元素到XML三(如本示例中)或查询。

您可以通过LINQ查询找到所需的元素。下一个示例显示了如何从ID为TestEntries的{​​{1}}中获取所有TestList

L1

此查询的结果对象具有包含有用属性的匿名类型。如果您希望使用var query = from e in doc.Root.Elements( ns + "TestEntries" ).Elements() where e.Attribute( "testListId" ).Value == "L1" select new { TestId = e.Attribute( "testId" ).Value, ExecutionId = e.Attribute( "executionId" ).Value }; foreach ( var testEntry in query ) { Console.WriteLine( testEntry.TestId + " " + testEntry.ExecutionId ); } 个对象,只需将XElement更改为select new ...

如果你想更新元素的值,找到它(看上面)并调用select e方法。

如果使用名称空间(如文件),则必须创建具有所需值的SetValue()对象,并将其与所需的所有元素名称连接。

要将更改保存到dist上的xml文件,请调用XNamespace方法。

LINQ to XML Overview in MSDN

相关问题