【问题标题】:Powershell can't set inner text of xmlelementPowershell 无法设置 xmlelement 的内部文本
【发布时间】:2020-02-14 09:55:09
【问题描述】:

我尝试制作一个脚本来更新 sharepoint 中的 web 部件,我找到了一些示例,但我遇到了 xml 问题,我必须将其传递给 web 部件。

请注意,我使用的 powershell 是 1.0。

$xmlDoc = New-Object xml;                
$newXmlElement = $xmlDoc.CreateElement("HtmlContent");       
$newXmlElement.InnerText="SomeValue";

所以这段脚本中断了,我收到一条错误消息:

在此对象上找不到属性“InnerText”;确保它 存在且可设置。

我真的不知道为什么它不起作用,有人知道吗?

我尝试在 Windows Powershell 命令行中执行此行,当我尝试设置内部文本时,它会抛出此红色错误消息。

【问题讨论】:

    标签: xml powershell sharepoint-2007


    【解决方案1】:

    我终于找到了一种方法,似乎在 PowerShell v1.0 中的对象 System.Xml.XmlElement,没有像 InnerText 等属性,所以我的方法如下:

     $xmlDoc=New-Object System.Xml.XmlDocument;             
     $xmlElement=$xmlDoc.CreateElement("HtmlElement"); 
     $xmlText = $xmlDoc.CreateTextNode($cewpNewContent)
     $xmlElement.AppendChild($xmlText);
    

    我希望这对其他人有用。

    【讨论】:

      【解决方案2】:

      当您尝试使用点表示法为现有元素赋值时遇到的错误是因为点表示法访问您所在的XmlNode 中的XmlElementXmlElement 没有InnerText,而XmlNode 有。

      如何使用 InnerText 创建和分配价值的示例

      $xmlDoc = New-Object xml;
      $newXmlElement = $xmlDoc.CreateNode("element", "HtmlContent", "")
      $newXmlElement.InnerText = "SomeValue"
      
      $secondXmlElement = $xmlDoc.CreateNode("element", "HtmlContentChild", "")
      $secondXmlElement.InnerText = "NewValue"
      
      $newXmlElement.AppendChild($secondXmlElement)
      $xmlDoc.AppendChild($newXmlElement)
      
      

      循环和节点访问示例

      foreach($node in $nodes) {
        if ($node.element -ne $null) {
          $node.element.InnerText = "this will throw error" # generates the error
          $node.element = "this is correct"                 # Correct way to add InnerText
        }
        else { 
          $elementToAdd = $xmlDoc.CreateNode("element", "element", "")
          $elementToAdd.InnerText = "This is correct"
          $node.AppendChild($elementToAdd)
        }
      }
      

      XmlDocument.CreateNode

      使用指定的节点类型、名称和 NamespaceURI(在您的示例中 NamespaceURI 为空)创建一个 XmlNode。

      XmlNode.AppendChild(XmlNode)

      将指定节点添加到该节点的子节点列表的末尾

      XmlNode

      XmlElement

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-07-01
        相关资源
        最近更新 更多