【问题标题】:How to check the node exists in xml and returns the string values by reading CDATA values如何检查xml中是否存在节点并通过读取CDATA值返回字符串值
【发布时间】:2012-02-13 10:34:17
【问题描述】:

我的字符串中包含以下 xml,并且我使用的是 c# 2.0

string strXML ="<?xml version="1.0"?>
<tcm:Error xmlns:tcm="http://www.tridion.com/ContentManager/5.0" ErrorCode="80040329" Category="17" Source="Kernel" Severity="2">
  <tcm:Line ErrorCode="80040329" Cause="false" MessageID="16137">
    <![CDATA[Unable to save Keyword (tcm:0-0-0).]]><tcm:Token>RESID_4574</tcm:Token><tcm:Token>RESID_15309</tcm:Token><tcm:Token>tcm:0-0-0</tcm:Token>
  </tcm:Line>
  <tcm:Line ErrorCode="80040329" Cause="true" MessageID="15200">
    <![CDATA[Name must be unique for items of type: Keyword within this Category and its BluePrint context. Source or sources  of conflict: tcm:236-215788-1024,tcm:237-215788-1024,tcm:241-215788-1024,tcm:243-215788-1024,tcm:423-215788-1024.]]><tcm:Token>RESID_15214</tcm:Token><tcm:Token>RESID_15309</tcm:Token><tcm:Token>RESID_15293</tcm:Token><tcm:Token>tcm:236-215788-1024,tcm:237-215788-1024,tcm:241-215788-1024,tcm:243-215788-1024,tcm:423-215788-1024</tcm:Token>
  </tcm:Line>
  <tcm:Details>
    <tcm:CallStack>
      <tcm:Location>UtilitiesBL.AssertUniqueTitle</tcm:Location>
      <tcm:Location>UtilitiesBL.AssertUniqueTitle</tcm:Location>
      <tcm:Location>KeywordBL.Create</tcm:Location>
      <tcm:Location>XMLState.Save</tcm:Location>
      <tcm:Location>Keyword.Save</tcm:Location>
    </tcm:CallStack>
  </tcm:Details>
</tcm:Error>"

现在我想写一个函数,它首先检查字符串strXML中是否有xml节点节点,如果没有这样的节点则返回“有效”,否则我的函数将返回从上面的xml中获取的字符串值。

所以我的返回结果将是“无法保存关键字 (tcm:0-0-0)。对于以下类型的项目,名称必须是唯一的:此类别中的关键字及其蓝图上下文。来源或冲突来源: tcm:236-215788-1024,tcm:237-215788-1024,tcm:241-215788-1024,tcm:243-215788-1024,tcm:423-215788-1024.”,这些文字是在 XML 中。

请推荐!!

谢谢。

MS

【问题讨论】:

    标签: c# .net xml xpath xmldocument


    【解决方案1】:

    用途:

    XmlDocument xml = new XmlDocument();
    xml.LoadXml(strXML);
    
    XmlNamespaceManager xmlnsManager = new XmlNamespaceManager(xml.NameTable);
    xmlnsManager.AddNamespace("tcm", "http://www.tridion.com/ContentManager/5.0");
    
    XmlNodeList res = xml.SelectNodes("//tcm:Line/text()", xmlnsManager);
    
    
    foreach (XmlNode item in res)
    {
        Console.WriteLine(item.InnerText);
    }
    

    【讨论】:

    • 好的,谢谢 Kirill,您能否建议在加载到 XmlDocument 之前如何检查字符串中是否存在特定节点。由于我的 strXML 可以是 xml 字符串以及普通字符串,这取决于返回的结果类型,我需要使用 .contains 还是有其他方法
    • @M.S,我建议你检查res.Count属性,例如:if (res.Count == 0) {...}。这比用Contains检查字符串要好。
    • 但是在将整个字符串上传到XmlDocument之前我们如何获得(res.Count == 0),请建议!!
    • @M.S,没有办法。
    • 好吧,我已经使用 contains 函数来检查它是否有 tcm:error 文本,然后我已经加载了 xml 文档..感谢您的帮助
    猜你喜欢
    • 1970-01-01
    • 2017-05-19
    • 1970-01-01
    • 1970-01-01
    • 2016-02-04
    • 2020-03-25
    • 2017-03-10
    • 2019-04-11
    • 1970-01-01
    相关资源
    最近更新 更多