How do I retrieve element text inside CDATA markup via XPath?

后端 未结 5 1179
南旧
南旧 2020-11-27 19:55

Consider the following xml fragment:


   

How do I retrieve the

5条回答
  •  醉酒成梦
    2020-11-27 20:41

    /Obj/Name/text() is the XPath to return the content of the CDATA markup.

    What threw me off was the behavior of the Value property. For an XMLNode (DOM world), the XmlNode.Value property of an Element (with CDATA or otherwise) returns Null. The InnerText property would give you the CDATA/Text content. If you use Xml.Linq, XElement.Value returns the CDATA content.

    string sXml = @"
    
        
        OtherName
    ";
    
    XmlDocument xmlDoc = new XmlDocument();
    xmlDoc.LoadXml( sXml );
    XmlNamespaceManager nsMgr = new XmlNamespaceManager(xmlDoc.NameTable);
    
    Console.WriteLine(@"XPath = /object/name" );
    WriteNodesToConsole(xmlDoc.SelectNodes("/object/name", nsMgr));
    
    Console.WriteLine(@"XPath = /object/name/text()" );
    WriteNodesToConsole( xmlDoc.SelectNodes("/object/name/text()", nsMgr) );
    
    Console.WriteLine(@"Xml.Linq = obRoot.Elements(""name"")");
    XElement obRoot = XElement.Parse( sXml );
    WriteNodesToConsole( obRoot.Elements("name") );
    

    Output:

    XPath = /object/name
            NodeType = Element
            Value = 
            OuterXml = 
            InnerXml = 
            InnerText = SomeText
    
            NodeType = Element
            Value = 
            OuterXml = OtherName
            InnerXml = OtherName
            InnerText = OtherName
    
    XPath = /object/name/text()
            NodeType = CDATA
            Value = SomeText
            OuterXml = 
            InnerXml =
            InnerText = SomeText
    
            NodeType = Text
            Value = OtherName
            OuterXml = OtherName
            InnerXml =
            InnerText = OtherName
    
    Xml.Linq = obRoot.Elements("name")
            Value = SomeText
            Value = OtherName
    

    Turned out the author of Visual XPath had a TODO for the CDATA type of XmlNodes. A little code snippet and I have CDATA support now. alt text

    MainForm.cs

    private void Xml2Tree( TreeNode tNode, XmlNode xNode)
    {
       ...
       case XmlNodeType.CDATA:
          //MessageBox.Show("TODO: XmlNodeType.CDATA");
          // Gishu                    
          TreeNode cdataNode = new TreeNode("![CDATA[" + xNode.Value + "]]");
          cdataNode.ForeColor = Color.Blue;
          cdataNode.NodeFont = new Font("Tahoma", 12);
          tNode.Nodes.Add(cdataNode);
          //Gishu
          break;
    

提交回复
热议问题