gpt4 book ai didi

c# - 改进从 xml 文件中获取数据

转载 作者:太空宇宙 更新时间:2023-11-03 18:42:06 25 4
gpt4 key购买 nike

我有一个这样的 XML 文件:

   <Document>
<Tests Count="4">
<Test>
<Name>test with a</Name>
<Type>VI test</Type>
<Result>Pass</Result>
</Test>
<Test>
<Name>test plot</Name>
<Type>Curve test</Type>
<Result>Fail</Result>
</Test>
<Test>
<Name>test fixture</Name>
<Type>Leakage test</Type>
<Result>Pass</Result>
</Test>
<Test>
<Name>test fixture</Name>
<Type>Leakage test</Type>
</Test>
</Tests>
</Document>

我做了一个类来包含其中的每个“测试”:

class TestGroup
{
public string TestName { get; set; }
public string TestType { get; set; }
public string TestResult { get; set; }
}

由于我对 XML 非常陌生,目前我得到这样的数据(ztr 是 XmlDocument):

public List<TestGroup> GetTestGroups()
{
List<TestGroup> TestNode = new List<TestGroup>();

string[] type_t = new string[GetTestsNumber()];
string[] name_t = new string[GetTestsNumber()];
string[] result_t = new string[GetTestsNumber()];

//name
string xpath = "/Document/Tests/Test";

int i = 0;

foreach (XmlElement Name in ztr.SelectNodes(xpath))
{
name_t[i] = Name.SelectSingleNode("Name").InnerText;
i++;
}
///////////

//result
xpath = "/Document/Tests/Test";

i = 0;

foreach (XmlElement Result in ztr.SelectNodes(xpath))
{
result_t[i] = Result.SelectSingleNode("Result").InnerText;
i++;
}
/////////////////
xpath = "/Document/Tests/Test";

i = 0;

foreach (XmlElement Type in ztr.SelectNodes(xpath))
{
type_t[i] = Type .SelectSingleNode("Type").InnerText;
i++;
}

int count = type_t.GetLength(0);

for (i = 0; i < count; i++)
{
LUTestGroup node = new LUTestGroup();
node.TestName = name_t[i];
node.TestType = type_t[i];
node.TestResult = result_t[i];

TestNode.Add(node);
}

return TestNode;
}

显然这种方式非常危险。它在 xml 时间中重复迭代,每次都向类添加一个属性。此外,如果您在示例 xml 文件中注明。最后一个 Test 没有 Result 节点,因此当我输入不同的 XML 文件时,我编写的代码有时会崩溃。

你能帮我写一个方法来安全地让列表被 XML 文件中所有可用的测试填充吗?如果其中任何一个没有节点,该方法就不会崩溃?并且必须很重要,一次完成工作!

谢谢

最佳答案

(如评论中所述。)

LINQ to XML 版本非常简单:

// Could use doc.Root.Element("Tests").Elements("Test") to be explicit
return doc.Descendants("Test")
.Select(x => new LUTestGroup {
TestName = (string) x.Element("Name"),
TestType = (string) x.Element("Type"),
TestResult = (string) x.Element("Result")
})
.ToList();

请注意,如果您给它一个空的 XElement 引用,从 XElementstring 的转换将返回空值,因此在您的“泄漏测试”中"情况下,您最终会得到一个 LUTestGroup,它的 TestResult 属性为空。

关于c# - 改进从 xml 文件中获取数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7767840/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com