[英]How to iterate through XML file
How do I iterate over all the elements of the XML tree, and access to them? 如何遍历XML树的所有元素并访问它们? What I mean is that the input gets unknown xml file, and the code itself it iterates not knowing the number of elements and branches.
我的意思是,输入获取了未知的xml文件,并且代码本身在不知道元素和分支数量的情况下进行了迭代。
I know that was a lot of answers on such topics and the solution was ready to implement the code, where the known structures xml. 我知道在这些主题上有很多答案,并且该解决方案已准备好实现代码,其中已知结构为xml。
This is a code which i am using: 这是我正在使用的代码:
class Program
{
static void Process(XElement element)
{
if (!element.HasElements)
{
Console.WriteLine(element.GetAbsoluteXPath());
}
else
{
foreach (XElement child in element.Elements())
{
Process(child);
}
}
}}
static void Main()
{
var doc = XDocument.Load("C:\\Users\\Błażej\\Desktop\\authors1.xml");
List<string> elements = new List<string>();
Program.Process(doc.Root);
Console.ReadKey();
}
public static class XExtensions
{
public static string GetAbsoluteXPath(this XElement element)
{
if (element == null)
{
throw new ArgumentNullException("element");
}
Func<XElement, string> relativeXPath = e =>
{
int index = e.IndexPosition();
string name = e.Name.LocalName;
return (index == -1) ? "/" + name : string.Format
(
"/{0}[{1}]",
name,
index.ToString()
);
};
var ancestors = from e in element.Ancestors()
select relativeXPath(e);
return string.Concat(ancestors.Reverse().ToArray()) +
relativeXPath(element);
}
public static int IndexPosition(this XElement element)
{
if (element == null)
{
throw new ArgumentNullException("element");
}
if (element.Parent == null)
{
return -1;
}
int i = 1;
foreach (var sibling in element.Parent.Elements(element.Name))
{ // czyli patrzymy na rodzeństwo, czy występują podobne np. au_id[1], au_id[2]
if (sibling == element)
{
return i;
}
else
{
i++;
}
}
throw new InvalidOperationException
("element has been removed from its parent.");
}
Now how can i add some elements to exisitng nodes by iterate ? 现在如何通过迭代将一些元素添加到现有节点中? It's possible ?
这是可能的 ?
As @strongbutgood mentioned, this is very generic. 正如@strongbutgood提到的,这是非常通用的。 May be below generic code helps
可能低于通用代码有帮助
Dim xdoc As New XDocument();
xdoc = XDocument.Parse(myXML);
// Adding new element
xdoc.Element(<Your_Parent_Node_Name>).Add(new XElement("<New_Element_Name>", "<New_Element_Value>"));
// Deleting existing element
xdoc.Descendants().Where(s =>s.Value == "<Element_To_Be_Removed>").Remove();
Hope this helps. 希望这可以帮助。
Please note that this is a generic answer and you will need to re-write as per your needs 请注意,这是一个通用答案,您将需要根据需要重新编写
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.