1

这是我需要做的:示例 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>

任何帮助/提示将不胜感激。我将知道传入的样本“ID”属性以及“样本名称”(元素的 CDATA)。

4

3 回答 3

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");
于 2010-07-16T01:21:10.670 回答
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>
于 2010-07-15T01:10:45.903 回答
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();
}
于 2010-07-16T17:12:23.773 回答