Removing nodes from an XmlDocument
81721 просмотра
6 ответа
The following code should find the appropriate project tag and remove it from the XmlDocument, however when I test it, it says:
The node to be removed is not a child of this node.
Does anyone know the proper way to do this?
public void DeleteProject (string projectName)
{
string ccConfigPath = ConfigurationManager.AppSettings["ConfigPath"];
XmlDocument configDoc = new XmlDocument();
configDoc.Load(ccConfigPath);
XmlNodeList projectNodes = configDoc.GetElementsByTagName("project");
for (int i = 0; i < projectNodes.Count; i++)
{
if (projectNodes[i].Attributes["name"] != null)
{
if (projectName == projectNodes[i].Attributes["name"].InnerText)
{
configDoc.RemoveChild(projectNodes[i]);
configDoc.Save(ccConfigPath);
}
}
}
}
UPDATE
Fixed. I did two things:
XmlNode project = configDoc.SelectSingleNode("//project[@name='" + projectName + "']");
Replaced the For loop with an XPath query, which wasn't for fixing it, just because it was a better approach.
The actual fix was:
project.ParentNode.RemoveChild(project);
Thanks Pat and Chuck for this suggestion.
Автор: FlySwat Источник Размещён: 13.11.2019 11:28Ответы (6)
65 плюса
Instead of
configDoc.RemoveChild(projectNodes[i]);
try
projectNodes[i].parentNode.RemoveChild(projectNodes[i]);
Автор: Pat
Размещён: 21.08.2008 05:38
2 плюса
2 плюса
Looks like you need to select the parent node of projectNodes[i] before calling RemoveChild.
Автор: Chuck Размещён: 21.08.2008 05:411 плюс
Is it possible that the project nodes aren't child nodes, but grandchildren or lower? GetElementsByTagName will give you elements from anywhere in the child element tree, IIRC.
Автор: Greg Hurlman Размещён: 21.08.2008 05:340 плюса
When you get sufficiently annoyed by writing it the long way (for me that was fairly soon) you can use a helper extension method provided below. Yay new technology!
public static class Extensions {
...
public static XmlNode RemoveFromParent(this XmlNode node) {
return (node == null) ? null : node.ParentNode.RemoveChild(node);
}
}
...
//some_long_node_expression.parentNode.RemoveChild(some_long_node_expression);
some_long_node_expression.RemoveFromParent();
Автор: Eugene Ryabtsev
Размещён: 20.06.2012 09:43
0 плюса
It would be handy to see a sample of the XML file you're processing but my guess would be that you have something like this
<Root>
<Blah>
<project>...</project>
</Blah>
</Root>
The error message seems to be because you're trying to remove <project>
from the grandparent rather than the direct parent of the project node
Вопросы из категории :
- c# Преобразовать десятичную в двойную?
- c# Как рассчитать чей-то возраст в C #?
- c# Как вы сортируете словарь по значению?
- c# В чем разница между int и Integer в Java и C #?
- c# Как создать новый экземпляр объекта из Типа
- .net Действительно ли опечатанные классы действительно предлагают преимущества?
- .net Setting Objects to Null/Nothing after use in .NET
- xml Обработка XML в Python
- xml Каков наилучший способ проверки XML-файла по сравнению с XSD-файлом?
- xml Removing nodes from an XmlDocument
- xml Как анализировать XML-файлы?
- xml XmlSerializer - произошла ошибка, отражающая тип
- xmldocument Как бы вы сравнили два XML-документа?
- xmldocument Как добавить пространство имен xml в документ xmldocument
- xmldocument Получение указанных значений узла из XML-документа
- xmldocument Windows Phone - XmlDocument не может быть найден