读取xml节点的子标签值

huangapple go评论73阅读模式
英文:

Reading xmlnode child tag value

问题

XmlDocument xmlDocNew = new XmlDocument();
XmlElement CATLOG = xmlDocNew.CreateElement("mappings");
XmlNode xmlNodeTab = xmltest.DocumentElement;
XmlNodeList xmlNodeListCD = xmlNodeTab.SelectNodes("//mapping");
foreach (XmlNode xmlNodeCD in xmlNodeListCD)
{
   string innerText = xmlNodeCD["a"].InnerText;
   string xmlNodeapp = xmlNodeCD["b/c/d"].InnerText;
}

在上面的代码中,我能够遍历所有的 "a" 标签元素,但是无法读取 "d" 标签的值。要读取 "d" 标签的值,你可以使用 "b/c/d" 的路径来访问,就像上面的代码示例中所示。这样,在 foreach 循环中,你可以同时获取 "a" 标签和其对应的 "d" 标签的值。

英文:

My xml file looks like below.

<mappings>
  <mapping>
    <a>a1value</a>
    <b>
      <c>
        <d>d1value</d>
        <e>e1value</e>
      </c>
    </b>
  </mapping>
  <mapping>
    <a>a2value</a>
    <b>
      <c>
        <d>d2value</d>
        <e>e2value</e>
      </c>
    </b>
  </mapping>
</mappings>

C# code to read the value of a,d tags.

XmlDocument xmlDocNew = new XmlDocument();
XmlElement CATLOG = xmlDocNew.CreateElement("mappings");
XmlNode xmlNodeTab = xmltest.DocumentElement;
XmlNodeList xmlNodeListCD = xmlNodeTab.SelectNodes("//mapping");
foreach (XmlNode xmlNodeCD in xmlNodeListCD)
{
   string innerText = xmlNodeCD["a"].InnerText;
   string xmlNodeapp = xmlNodeCD["//b/c/d"].InnerText;
}

With the above code i am able to iterate through all the "a" tag elements.
But I am not able to read "d" tag value.
How do I read the value of "d" tag?

When I iterate through each element in the foreach loop, I want to get the value of "a" tag and its corresponding "d" tag value.

答案1

得分: 0

这段代码查看每个映射,并在其下查找标签 ad 的值。还要注意,如果您想查找“sub”标签并仅获取这些子项,您必须使用 .// 而不仅仅是 //。点符号提取位于当前节点下的节点。

XmlDocument doc = new XmlDocument();
doc.Load($@"{Directory.GetParent(Environment.CurrentDirectory).Parent.Parent.FullName}\json.txt");

var nodes = doc.SelectNodes("//mapping");
foreach (XmlNode node in nodes)
{
    var aNodes = node.SelectNodes(".//a");
    foreach (XmlNode aNode in aNodes)
        Console.WriteLine(aNode.InnerText);

    // 如果您知道 .//b/c/d 下只有一个节点,请使用 SelectSingleNode。
    Console.WriteLine(node.SelectSingleNode(".//b/c/d").InnerText);
}

输出

a1value
d1value
a2value
d2value

注意:

a 标签在某种程度上是 d 标签的兄弟,并且它们的单一父元素是 mapping 元素。如果您获取所有映射节点,然后逐个处理这些节点,您将获得最佳结果。

英文:

This code looks at each of the mapping and under it, looks up the value for tags a and d. Also note that if you want to look up 'sub' tags and only get these child items, you have to use .// instead of just //. Dot notation pulls node "under" the current node.

    XmlDocument doc = new XmlDocument();
    doc.Load($@"{Directory.GetParent(Environment.CurrentDirectory).Parent.Parent.FullName}\json.txt");

    var nodes = doc.SelectNodes("//mapping");
    foreach (XmlNode node in nodes)
    {
        var aNodes = node.SelectNodes(".//a");
        foreach (XmlNode aNode in aNodes)
            Console.WriteLine(aNode.InnerText);

        // If you know there will only be one node at .//b/c/d, use SelectSingleNode instead.
        Console.WriteLine(node.SelectSingleNode(".//b/c/d").InnerText);
    }

Output

a1value
d1value
a2value
d2value

Note:

a tag is sort of a sibling of d tag and their singular parent is the mapping element. You would get best results if you got all the mapping nodes and then worked through those.

答案2

得分: 0

自 .Net 3.5 开始,引入了 Linq 和 Linq To XML,使 XML 解析变得更加简便。使用 Linq To XML,您可以这样读取它:

void Main()
{
    var s = @"<mappings>
      <mapping>
        <a>a1value</a>
        <b>
          <c>
            <d>d1value</d>
            <e>e1value</e>
          </c>
        </b>
      </mapping>
      <mapping>
        <a>a2value</a>
        <b>
          <c>
            <d>d2value</d>
            <e>e2value</e>
          </c>
        </b>
      </mapping>
    </mappings>";
    var data = from x in XDocument.Parse(s).Descendants("mapping")
               select new {
                   a = (string)x.Element("a"),
                   d = (string)x.Element("b").Element("c").Element("d")
               };
    
    foreach (var e in data)
    {
        Console.WriteLine($"{e.a}, {e.d}");
    }
}

如果您有一个与此结构匹配的类,如下所示:

public class MyData
{ 
    public string A { get; set; }
    public string D { get; set; }
}

然后,您可以像这样使用这个类,而不是匿名类型:

var data = from x in XDocument.Parse(s).Descendants("mapping")
           select new MyData {
               A = (string)x.Element("a"),
               D = (string)x.Element("b").Element("c").Element("d")
           };

foreach (var e in data)
{
    Console.WriteLine($"{e.A}, {e.D}");
}

PS:由于您获得的是一个 IEnumerable,您可以直接将数据绑定到 DataGridViewListBox 等(...DataSource = data.ToList())。

英文:

Since .Net 3.5 there is Linq and Linq To XML which makes XML parsing easier. With Linq To XML you could read it as:

    void Main()
    {
    	var s = @&quot;&lt;mappings&gt;
      &lt;mapping&gt;
        &lt;a&gt;a1value&lt;/a&gt;
        &lt;b&gt;
          &lt;c&gt;
            &lt;d&gt;d1value&lt;/d&gt;
            &lt;e&gt;e1value&lt;/e&gt;
          &lt;/c&gt;
        &lt;/b&gt;
      &lt;/mapping&gt;
      &lt;mapping&gt;
        &lt;a&gt;a2value&lt;/a&gt;
        &lt;b&gt;
          &lt;c&gt;
            &lt;d&gt;d2value&lt;/d&gt;
            &lt;e&gt;e2value&lt;/e&gt;
          &lt;/c&gt;
        &lt;/b&gt;
      &lt;/mapping&gt;
    &lt;/mappings&gt;&quot;;
    	var data = from x in XDocument.Parse(s).Descendants(&quot;mapping&quot;)
    			   select new {
    			   	a=(string)x.Element(&quot;a&quot;),
    				d=(string)x.Element(&quot;b&quot;).Element(&quot;c&quot;).Element(&quot;d&quot;)
    				};
    	
    	foreach (var e in data)
    	{
    		Console.WriteLine($&quot;{e.a}, {e.d}&quot;);
    	}
    }

With a file, instead of .Parse, you would use .Load( filename ).

Output:

a1value, d1value
a2value, d2value

If you have a class matching this structure, like:

public class MyData
{ 
	public string A { get; set; }
	public string D { get; set; }
}

Then instead of the anonymous type you could use this class like so:

var data = from x in XDocument.Parse(s).Descendants(&quot;mapping&quot;)
		   select new MyData {
		   	A=(string)x.Element(&quot;a&quot;),
			D=(string)x.Element(&quot;b&quot;).Element(&quot;c&quot;).Element(&quot;d&quot;)
			};

foreach (var e in data)
{
	Console.WriteLine($&quot;{e.A}, {e.D}&quot;);
}

PS: Since you are getting an IEnumerable, you could directly bind data to a DataGridView, ListBox ... ( ...DataSource = data.ToList()).

huangapple
  • 本文由 发表于 2020年1月3日 15:20:39
  • 转载请务必保留本文链接:https://go.coder-hub.com/59574630.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定