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

时间:2013-04-22 12:28:51

标签: c# asp.net .net

我有以下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>

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

How to read attribute value from XmlNode in C#?

我需要这样的输出

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

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

10 个答案:

答案 0 :(得分:8)

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

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

答案 1 :(得分:4)

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

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

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

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"

答案 2 :(得分:4)

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

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);
                  }
              }  
          }

答案 3 :(得分:3)

假设您有XmlDocument,您可以使用XPath:

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

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

答案 4 :(得分:2)

试试这个:

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();

然后:

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

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

答案 5 :(得分:2)

您可以使用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;
    // ...
}

答案 6 :(得分:0)

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

答案 7 :(得分:0)

你可以尝试一下吗?

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")))
   {

   }
}

答案 8 :(得分:0)

试试这个..

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);
        }

答案 9 :(得分:-4)

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.