我正在尝试剥离我的 XML 并仅保留 String Keep 数组中的节点
输入 XML 是
<Employees>
<Employee>
<EmpId>1</EmpId>
<Name>Sam</Name>
<Sex>Male</Sex>
<Address>
<Country>USA</Country>
<Zip>95220</Zip>
</Address>
</Employee>
<Employee>
<EmpId>2</EmpId>
<Name>Lucy</Name>
<Sex>Female</Sex>
<Address>
<Country>USA</Country>
<Zip>95220</Zip>
</Address>
</Employee>
</Employees>
我需要的输出是
<Employees>
<Employee>
<EmpId>1</EmpId>
<Sex>Male</Sex>
<Address>
<Zip>95220</Zip>
</Address>
</Employee>
<Employee>
<EmpId>2</EmpId>
<Sex>Female</Sex>
<Address>
<Zip>95220</Zip>
</Address>
</Employee>
</Employees>
我的代码如下。
private void button1_Click(object sender, EventArgs e)
{
XmlDocument xDoc = new XmlDocument();
xDoc.Load(XML_Path);
// xDoc.Load();
XmlNodeList xNodes = xDoc.SelectNodes("Employees/Employee");
XmlDocument doc = new XmlDocument();
XmlNode docNode = doc.CreateXmlDeclaration("1.0", "UTF-8", null);
doc.AppendChild(docNode);
XmlNode employeesNode = doc.CreateElement("Employees");
doc.AppendChild(employeesNode);
string s =null;
string keep = "EmpId,Sex,Address/Zip";
string[] strArr = keep.Split(',');
foreach(XmlNode xN in xNodes)
{
XmlNode employeeNode = doc.CreateElement("Employee");
employeesNode.AppendChild(employeeNode);
foreach (string str in strArr)
{
XmlNode xNod = xN.SelectSingleNode(str);
employeeNode.AppendChild(xNod);
}
}
richTextBox1.Text = doc.ToString();
}
我在内部 foreach 循环中遇到一个奇怪的错误,它不会添加新节点,谁能告诉我我在做什么错。
谢谢