我必须解析C#中的xml
<Packages>
<Package>
<PackageName>Create_Staging_Table</PackageName>
<SequenceID>1</SequenceID>
<AlwaysRun>True</AlwaysRun>
</Package>
<Package>
<PackageName>Indigo_Staging_Load</PackageName>
<SequenceID>2</SequenceID>
<AlwaysRun>True</AlwaysRun>
</Package>
<Package>
<PackageName>Indiogo_Load_Package</PackageName>
<SequenceID>3</SequenceID>
<AlwaysRun>True</AlwaysRun>
</Package>
</Packages>
我试过了
XmlDocument doc = new XmlDocument();
doc.Load(filePath);
XmlNode PackagesListNode = doc.SelectSingleNode("/Packages");
XmlNodeList Packages = PackagesListNode.SelectNodes("Package");
foreach (XmlNode node in Packages)
{
TableLoadInstruction instruction = new TableLoadInstruction();
instruction.PackageName = node.Attributes.GetNamedItem("PackageName").Value;
instruction.Sequence = Convert.ToInt16(node.Attributes.GetNamedItem("SequenceID").Value);
instruction.AlwaysRun = Convert.ToBoolean(node.Attributes.GetNamedItem("AlwaysRun").Value);
loadInstructions.Add(instruction);
}
我在node.Attributes.GetNamedItem(“PackageName”)收到类似“对象引用未设置为对象实例”的错误。自node.Attributes.GetNamedItem(“PackageName”)以来的值为'null'
答案 0 :(得分:1)
您尝试做的事情不会起作用,因为PackageName不是属性。您必须查看Package的子节点。
答案 1 :(得分:1)
终于得到了解决方案
XmlDocument doc = new XmlDocument();
doc.Load(filePath);
XmlNode PackagesListNode = doc.SelectSingleNode("/Packages");
XmlNodeList Packages = PackagesListNode.SelectNodes("Package");
foreach (XmlNode node in Packages)
{
TableLoadInstruction instruction = new TableLoadInstruction();
instruction.PackageName = node.SelectSingleNode("PackageName").InnerText;
instruction.Sequence = Convert.ToInt16(node.SelectSingleNode("SequenceID").InnerText);
instruction.AlwaysRun = Convert.ToBoolean(node.SelectSingleNode("AlwaysRun").InnerText);
loadInstructions.Add(instruction);
}
答案 2 :(得分:0)
你正在寻找PackageName,这是阳极进入node.Attributes,所以我认为你永远不会得到这个xml的值。这是你的问题吗?