Here's what I need to do: sample XML (not sure if it displays right here)
<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">Sa开发者_如何学编程mple45</Sample>
</Tag>
</Tags>
I want to delete:
<Sample ID="135" Count="1">Sample99</Sample>
and pass the XML back as:
<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>
Any help/tips will be appreciated. I will be knowing the incoming Sample 'ID' attribute, as well as the 'SampleName' (element's CDATA).
You should be able to do something like this in 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");
Executing this stylesheet against the XML will produce the desired ouptut:
<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>
Thanks for the answer Mads Hansen, it was very helpful!!! Thanks to all others too! Yes my path was wrong. Your code works, however in my case, doing 'save' was causing an error now. I was using the same string to save the information (not a newfile.xml, as you mentioned in the example answer). Perhaps that was causing me trouble, Here is what I did to solve this new issue:
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();
}
精彩评论