如何从 C# 中的 xml 读取特定节点?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16147142/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 00:08:39  来源:igfitidea点击:

How to read a particular node from xml in C#?

c#asp.net.net

提问by

I have following XML:

我有以下 XML:

<Loop Name="MasterData">
  <Loop Name="SlaveData">
    <Segment Name="AAA">
      <Node1>hello</Node1>
      <Node2>john</Node2>
      <Node3>hi</Node3>
      <Node4>marry</Node4>
    </Segment>
    <Segment Name="BBB">
      <Node1>00</Node1>
      <Node2> </Node2>
      <Node3>00</Node3>
      <Node4> </Node4>
    </Segment> 
   </Loop>
</Loop>

I have to read value of each Node i.e, Node1, Node2, Node3, Node4 which are under Segment node whose attribute ie Name = "AAA". How can I do this. I am referring following link from stackoverflow but thats not working for me.

我必须读取每个节点的值,即 Node1、Node2、Node3、Node4,它们在属性 ie 的 Segment 节点下Name = "AAA"。我怎样才能做到这一点。我指的是来自 stackoverflow 的以下链接,但这对我不起作用。

How to read attribute value from XmlNode in C#?

如何从 C# 中的 XmlNode 读取属性值?

I need output like this

我需要这样的输出

Lets I have four sting variables strNode1, strNode2, strNode3, strNode4. I want to store values in above four variables like following

让我有四个刺痛变量strNode1, strNode2, strNode3, strNode4。我想将值存储在以上四个变量中,如下所示

strNode1 = "hello"
strNode2 = "john"
strNode3 = "hi"
strNode4  = "marry"

采纳答案by Casperah

I found a simple solution for my problem

我为我的问题找到了一个简单的解决方案

XmlNodeList xnList = doc.SelectNodes("/Loop/Loop/Segment[@Name='AAA']");
          foreach (XmlNode xn in xnList)
          {
              if (xn.HasChildNodes)
              {
                  foreach (XmlNode item in xn.ChildNodes)
                  {
                      Console.WriteLine(item.InnerText);
                  }
              }  
          }

回答by Rich O'Kelly

I'd recommend using an XDocument (NB specific filtering based on parent nodes etc omitted):

我建议使用 XDocument(基于父节点等的 NB 特定过滤被省略):

var document = XDocument.Load(path);
var nodes = document.Descendents().Where(e => e.Name.LocalName.StartsWith("Node"));

Update to include filtering of parent element

更新以包括对父元素的过滤

var nodes = document.Descendents()
                    .Where(e => e.Atrributes().Any(a => a.Name.localName == "Name" && a.Value == "AAA"))
                    .SelectMany(e => e.Descendents().Where(e => e.Name.LocalName.StartsWith("Node"));
var values = nodes.Select(n => n.Value).ToList(); // This will be a list containing "hello", "john, "hi", "marry"

回答by Erwin

If you ever used linq-to-entities or linq-to-sql, there is a linq-to-xmlyou can use.

如果您曾经使用过 linq-to-entities 或 linq-to-sql,则可以使用linq-to-xml

回答by Thorsten Dittmar

Assuming you have an XmlDocumentyou can use XPath like:

假设你有一个XmlDocument你可以使用 XPath 像:

XmlNode node = doc.SelectSingleNode("//Segment[@Name='AAA']");

to get the Segmentnode and then iterate all its children in a loop.

获取Segment节点,然后在循环中迭代其所有子节点。

回答by Hossein Narimani Rad

Try this:

尝试这个:

System.Xml.Linq.XDocument doc = XDocument.Load(your file);

var nodes = 
     doc.Element("Loop").Element("Loop").Elements("Segment")
                .Where(input => (string)input.Attribute("Name") == "AAA")
                .Select(input => input.Elements()).ToList();

Then:

然后:

List<string> result = new List<string>();

foreach (List<XElement> item in nodes)
{
    result.AddRange(item.Select(i => i.Value));
}

回答by phadaphunk

You could use XmlDocumentto load your xml as an object and then query the specific nodes you want using XPath. Your xpath query (which I can't test right now) would probably look like this.

您可以使用XmlDocument将您的 xml 作为对象加载,然后使用XPath查询您想要的特定节点。您的 xpath 查询(我现在无法测试)可能看起来像这样。

XmlNodeList xNodes = xmlDocument.SelectNodes("//Segment[@Name = 'AAA']");

回答by Mehdi Bugnard

Do you can try this ?

你可以试试这个吗?

XDocument xmlFile = XDocument.Load("myFile.xml");
foreach (var nodeSegment in xmlFile.Descendants("Loop"))
{
   foreach (var nodes in nodeSegment.Descendants().Where(e => e.Name.LocalName.StartsWith("Node")))
   {

   }
}

回答by Casperah

You could use XmlDocument and XPath:

您可以使用 XmlDocument 和 XPath:

XmlDocument doc = new XmlDocument();
doc.Load(xml);
foreach(XmlNode node in doc.SelectNodes("//Segment[@Name='AAA']/node()"))
{
    string name = node.Name;
    string value = node.innerText;
    // ...
}

回答by Asif Iqbal

Try this out..

试试这个..

List<string> nodeDetails = new List<string>();

       var nodes = from n in XDocument.Load(@"D:\pfXml.xml")
                                              .Element("Loop")
                                              .Element("loop")
                                              .Elements("Segment")
                                      where (string)n.Attribute("Name") == "AAAA"
                                      select new
                                      {
                                          n1 = n.Element("Node1").Value,
                                          n2 = n.Element("Node2").Value,
                                          n3 = n.Element("Node3").Value,
                                          n4 = n.Element("Node4").Value
                                      };
        foreach (var node in nodes)
        {
            nodeDetails.Add(node.n1);
            nodeDetails.Add(node.n2);
            nodeDetails.Add(node.n3);
            nodeDetails.Add(node.n4);
        }

回答by Kiran Jadhav

This might help u,
<br/>
My XML File Is like:
<br/>
< People>
<br/>  
< GroupName Name="NY"><br/>  
    < Address1>1540 Broadway< /Address1> <br/> 
    < State>NY< /State>  <br/>
    < City>New York< /City>  <br/>
    < ZipCode>10036< /ZipCode>  <br/>
  < /GroupName><br/><br/>

  < GroupName Name="TX">  <br/>
    < Address1>1755 Wittington Place< /Address1> <br/>   
    < State>TX< /State>  <br/>
    < City>Dallas< /City> <br/>
    < ZipCode>75234< /ZipCode>  <br/>
  < /GroupName><br/><br/>

  < GroupName Name="Gr">  <br/>
    < Address1>124 Platinum< /Address1>  <br/>
    < State>MH< /State>  <br/>
    < City>Mum< /City>  <br/>
    < ZipCode>400221< /ZipCode>  <br/>
  < /GroupName><br/><br/>
< /People><br/>




In Code behind file :<br/>


 System.Xml.Linq.XDocument doc = XDocument.Load(Path of XML);

            var xmlData = (from p in doc.Descendants("People").Descendants("GroupName")
                           let Name = (p.Attribute("Name").Value)
                           where Name.Equals("NY")
                           select new {Name = Name, Add = p.Element("Address1").Value, State = p.Element("State").Value}).Single();
<br/><br/><br/>
            strName = xmlData.Name;<br/>
            strAdd = xmlData.Add;<br/>
            strState = xmlData.State;<br/>

<br/>
Hope this will be perfect answer for your question.