简体   繁体   中英

How to get the specific innertext of my xmlnode in C#?

I have one Xml Node for my processing.The following one is my xml node.

<w:p>
 <w:r>
   <w:t>
     Text1
   </w:t>
  </w:r>
  <w:r>
    <w:pict>
       <w:p>
         <w:r>
           <w:t>
             text2
            </w:t>
          </w:r>
        </w:p>
      </w:pict>
   </w:r>
 <w:r>
   <w:t>
     Text3
   </w:t>
  </w:r>
  <w:r>
</w:p>

Now i want to get the inner text from <w:p><w:r><w:t> only and not from <w:p><w:r><w:pict><w:p><w:r><w:t> .

So, my required output is Text1Text3

My C# code is :

 XmlNodeList pNode = xDoc.GetElementsByTagName("w:p");
 for (int i = 0; i < pNode.Count; i++)
 {
    if(i==0)  //This is my criteria 
    {
      XmlNode firstNode = pNode[i];
      string innerText=firstNode.innerText.toString().Trim();
    }
 }

But it returns all the inner text like Text1Text2Text3

Please guide me to get out of this issue?

您可以使用XPath :(我认为以下方法适用于您)

w:p/w:r/w:t

You need to check for each element p that none of its anchestors is a pict element.

var result = XElement.Load(@"path-to-your-xml")
                     .Descendants("t")
                     .Where(e => !e.AnchestorsAndSelf().Any(a => a.Name.LocalName == "pict"));

I recommend you use XDocument (if you have .NET 3.5 or higher). This code gets values of all elements that have pattern p/r/t but don't have pict/p/r/t :

        // Use this if you're loading XML from a string
        XDocument doc = XDocument.Parse(inputString);
        // Use this if you're loading XML from a file
        //XDocument doc = XDocument.Load(<filepath>);

        var pElements = doc.Root
            .Descendants()
            .Where(el => el.Name.LocalName == "p" && el.Parent.Name.LocalName != "pict");

        List<string> innerTexts = new List<string>();
        foreach(XElement p in pElements)
        {
            var rElements =  p.Elements().Where(el => el.Name.LocalName == "r");
            foreach(XElement r in rElements)
            {
                var tElements = r.Elements().Where(el => el.Name.LocalName == "t");
                innerTexts.AddRange(tElements.Select(el => el.Value).ToArray());
            }
        }

I used LocalName since no information on w namespace was provided.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM