这是我需要做的事情: 示例XML(不确定它是否显示在此处)
<Tags>
<Tag ID="0" UserTotal="1" AllowMultipleSelect="1">
<Name>BaseSamples</Name>
<Sample ID="546" Count="1">Sample1 </Sample>
<Sample ID="135" Count="1">Sample99</Sample>
<Sample ID="544" Count="1">Sample2</Sample>
<Sample ID="5818" Count="1">Sample45</Sample>
</Tag>
</Tags>
我想删除:
<Sample ID="135" Count="1">Sample99</Sample>
并将XML传回:
<Tags>
<Tag ID="0" UserTotal="1" AllowMultipleSelect="1">
<Name>BaseSamples</Name>
<Sample ID="546" Count="1">Sample1 </Sample>
<Sample ID="544" Count="1">Sample2</Sample>
<Sample ID="5818" Count="1">Sample45</Sample>
</Tag>
</Tags>
任何帮助/提示将不胜感激。我将知道传入的Sample'ID'属性,以及'SampleName'(元素的CDATA)。
答案 0 :(得分:2)
你应该可以在C#
中做这样的事情 XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load("XMLFile.xml");
XmlNode node = xmlDoc.SelectSingleNode("/Tags/Tag/Sample[@ID='135']");
XmlNode parentNode = node.ParentNode;
if (node != null) {
parentNode.RemoveChild(node);
}
xmlDoc.Save("NewXMLFileName.xml");
答案 1 :(得分:1)
对XML执行此样式表将产生所需的输出:
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output indent="yes" />
<!--identity template copies all content forward -->
<xsl:template match="@*|node()">
<xsl:copy>
<xsl:apply-templates select="@*|node()"/>
</xsl:copy>
</xsl:template>
<!--empty template will prevent this element from being copied forward-->
<xsl:template match="Sample[@ID='135']"/>
</xsl:stylesheet>
答案 2 :(得分:1)
感谢Mads Hansen的回答,这非常有帮助! 还要感谢所有其他人! 是的,我的道路是错的。 您的代码有效,但在我的情况下,执行“保存”现在会导致错误。 我使用相同的字符串来保存信息(不是newfile.xml,正如您在示例答案中提到的那样)。也许这给我带来了麻烦,以下是我为解决这个新问题所做的工作:
XmlDocument workingDocument = new XmlDocument();
workingDocument.LoadXml(sampleInfo); //sampleInfo comes in as a string.
int SampleID = SampleID; //the SampleID comes in as an int.
XmlNode currentNode;
XmlNode parentNode;
// workingDocument.RemoveChild(workingDocument.DocumentElement.SelectSingleNode("/Tags/Tag/Sample[@ID=SampleID]"));
if (workingDocument.DocumentElement.HasChildNodes)
{
//This won't work: currentNode = workingDocument.RemoveChild(workingDocument.SelectSingleNode("//Sample[@ID=" + SampleID + "]"));
currentNode = workingDocument.SelectSingleNode("Tags/Tag/Sample[@ID=" + SampleID + "]");
parentNode = currentNode.ParentNode;
if (currentNode != null)
{
parentNode.RemoveChild(currentNode);
}
// workingDocument.Save(sampleInfo);
sampleInfo = workingDocument.InnerXml.ToString();
}