使用System.XML将具有属性的子元素添加到XML

时间:2016-08-10 09:12:08

标签: c# xml system.xml

我有以下XML文件:

<testsuite name="Tests" rxversion="5.4.5.19886" id="d1203701-d61c-4ae6-932d-faa44beb925a" reportfilename="%S_%Y%M%D_%T.rxlog" reporttemplatefolder="" reportxslfilename="" placescreenshotsinfolder="True" ReportTime="RelativeToTestSuiteStartTime" reportwriteinterval="30000ms" reportcompress="False" enabletracingscreenshots="True" TracingScreenshotMode="Foreground" TracingScreenshotQuality="40" reportlevel="Info;20" warnunboundvariables="False">
<testconfigurations default="TestRun">
    <testconfiguration name="TestRun" />
</testconfigurations>
</testsuite>

以下代码更新XML:

var xe = new XmlDocument();
xe.Load("Z:\\Tests\\Tests.rxtst");

string testconfig = "//testsuite/testconfigurations/testconfiguration";
string testconfigend = "//testsuite";

XmlNode tc = xe.SelectSingleNode(testconfig);
XmlNode tcend = xe.SelectSingleNode(testconfigend);

XmlElement xs = xe.CreateElement("testcase");
xs.SetAttribute("id", "450c9a87-75dc-4538-bc2c-6df6eb359d2a");
XmlNode par = tc.ParentNode;
par.InsertBefore(xs, tc.LastChild);

xe.Save("st.rxtst");

使用此代码,我得到以下xml输出:

<testsuite name="Tests" rxversion="5.4.5.19886" id="d1203701-d61c-4ae6-932d-faa44beb925a" reportfilename="%S_%Y%M%D_%T.rxlog" reporttemplatefolder="" reportxslfilename="" placescreenshotsinfolder="True" ReportTime="RelativeToTestSuiteStartTime" reportwriteinterval="30000ms" reportcompress="False" enabletracingscreenshots="True" TracingScreenshotMode="Foreground" TracingScreenshotQuality="40" reportlevel="Info;20" warnunboundvariables="False">
    <testconfigurations default="TestRun">
        <testconfiguration name="TestRun" />
        <testcase id="450c9a87-75dc-4538-bc2c-6df6eb359d2a" />
    </testconfigurations>
</testsuite>

我想将testcase元素添加为testconfiguration的子元素。输出应该是:

<testsuite name="Tests" rxversion="5.4.5.19886" id="d1203701-d61c-4ae6-932d-faa44beb925a" reportfilename="%S_%Y%M%D_%T.rxlog" reporttemplatefolder="" reportxslfilename="" placescreenshotsinfolder="True" ReportTime="RelativeToTestSuiteStartTime" reportwriteinterval="30000ms" reportcompress="False" enabletracingscreenshots="True" TracingScreenshotMode="Foreground" TracingScreenshotQuality="40" reportlevel="Info;20" warnunboundvariables="False">
    <testconfigurations default="TestRun">
        <testconfiguration name="TestRun">
            <testcase id="450c9a87-75dc-4538-bc2c-6df6eb359d2a"/>
        </testconfiguration>
    </testconfigurations>
</testsuite>

如何将testcase元素添加为testconfiguration的孩子?

更新 现在正确设置了id,但该元素未添加为testconfiguration节点的子节点。

1 个答案:

答案 0 :(得分:2)

您需要XmlElement.SetAttribute向元素添加属性,将值设置为XmlElement.InnerText会替换嵌套内容。

xs .SetAttribute("id", "450c9a87-75dc-4538-bc2c-6df6eb359d2a");

另外,您也可以Linq使用Xml

XDocument doc = XDocument.Parse(input);

foreach(var element in doc.Descendants("testconfiguration"))
{
    element.Add(new XElement("testcase", new XAttribute("id","450c9a87-75dc-4538-bc2c-6df6eb359d2a") ));
}

选中此Demo