[英]How to remove a tag from XML Document using C#?
<sg>
<userdata>
<data>
<tag name="gf" description="fg" nodeid=" {2F2CC6951E2B4EEA979F357164CB73E5}" controllerid="" keytype="" mask="" track="widthsegment" numkey="" interpolator="" frame="" aindex="1" number="1">
<![CDATA[ //sg/objects/object[@id=" {2F2CC6951E2B4EEA979F357164CB73E5}"]/params/param[@name="widthsegment"]
]]>
</tag>
<tag name="gf" description="fg" nodeid=" {2F2CC6951E2B4EEA979F357164CB73E5}" controllerid="" keytype="" mask="" track="widthsegment" numkey="" interpolator="" frame="" aindex="1" number="2">
<![CDATA[ //sg/objects/object[@id=" {2F2CC6951E2B4EEA979F357164CB73E5}"]/params/param[@name="widthsegment"]
]]>
</tag>
</data>
</userdata>
</sg>
I want to remove the " tag " - tag from this how to do this 我想从此删除“标签”-标签
I made like this 我做了这样
updatedData.SelectSingleNode("//tag[@name='" + 1 + "']").RemoveAll();
But still tag comes in this .. i mean empty tag .. how to remove that 但是这个仍然是标签..我的意思是空标签..如何删除
after that 之后
<sg>
<userdata>
<data>
<tag /> --- This is wat i want to remove... how to remove this
<tag name="gf" description="fg" nodeid=" {2F2CC6951E2B4EEA979F357164CB73E5}" controllerid="" keytype="" mask="" track="widthsegment" numkey="" interpolator="" frame="" aindex="1" number="2">
<![CDATA[ //sg/objects/object[@id=" {2F2CC6951E2B4EEA979F357164CB73E5}"]/params/param[@name="widthsegment"]
]]>
</tag>
</data>
XmlNodeList nodes = updatedData.GetElementsByTagName("tagname");
foreach (XmlNode node in nodes)
{
if (node.ChildNodes.Count == 0)
node.RemoveAll();
else
UpdateDoc.InnerXml = node.OuterXml;
}
I solved this ... 我解决了这个...
var xmlDoc = XDocument.Load("filename.xml");
var element = (
from x in xmlDoc.Root.Elements("elemnt-name")
where x.Element("tage-name").Value == "xxxx"
select x
).FirstOrDefault();
element.Remove();
xmlDoc .Save("filename.xml");
Your XPath is strange: 您的XPath很奇怪:
"//tag[@name='" + 1 + "']"
It will select all tag
elements that have a name
attribute with the value of 1. There are none in your example. 它将选择所有name
属性值为1的tag
元素。您的示例中没有任何元素。
You are also using SelectSingleNode
which will only select a single node. 您还使用SelectSingleNode
,它将仅选择一个节点。
The XPath should be "//tag"
if you wish to select them all, and you should be using SelectNodes
instead. 如果希望全部选择XPath,则XPath应该为"//tag"
,而应该使用SelectNodes
。
this is how you do the loading for xdocument to XmlNodeList 这是将xdocument加载到XmlNodeList的方法
XDocument doc = XDocument.Load(@"C:\Users\sghaida\Documents\Visual Studio 2008\Projects\testing-ws-1\XMLParser\config.xml");
XmlDocument xmlDoc = new XmlDocument();
XmlNodeReader nodeReader = (XmlNodeReader)doc.CreateReader();
xmlDoc.ReadNode(nodeReader);
XmlNodeList xmlnodeList = xmlDoc.SelectNodes("node");
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.