簡體   English   中英

PowerShell 添加

[英]PowerShell Adding

我需要你的幫助,請

我正在解析另一個 xml 文件,刪除我不需要的節點,並保存相同的文檔,但它刪除了 xml 聲明。

有什么辦法不去掉嗎? 還是重新添加?

我有這個小 xml 文件。 但我需要在第一行添加這個聲明:

<'?xml version="1.0" encoding="UTF-8" standalone="yes"?'>

我嘗試了很多方法,但是還是給了-me錯誤或者異常

<METATRANSCRIPT:METATRANSCRIPT xmlns:METATRANSCRIPT="http://www.mpi.nl/IMDI/Schema/IMDI" xmlns="http://www.mpi.nl/IMDI/Schema/IMDI" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" ArchiveHandle="hdl:2196/00-0000-0000-0013-5776-9" Date="2018-12-17" FormatId="IMDI 3.04" Originator="CMDI Maker by CLASS - Cologne Language Archive Services" Type="SESSION" Version="1.0" xsi:schemaLocation="http://www.mpi.nl/IMDI/Schema/IMDI http://www.mpi.nl/IMDI/Schema/IMDI_3.0.xsd">
   <Location>
     <Continent Link="http://www.mpi.nl/IMDI/Schema/Continents.xml"  Type="ClosedVocabulary">Oceania</Continent>
     <Country Link="http://www.mpi.nl/IMDI/Schema/Countries.xml"  Type="OpenVocabulary">Vanuatu</Country>
     <Region>Shefa Province</Region>
     <Address>Tongamea village Emae island</Address>
  </Location>
</METATRANSCRIPT:METATRANSCRIPT>

這是我的代碼:

     [xml]$File = gc c:\\Source\Fakamae_2018005_KM.xml -Raw


     foreach ($meta in $File)
     {$File =($meta.xml,[xml]$File.GetElementsByTagName("METATRANSCRIPT:METATRANSCRIPT")[0].OuterXml)}
              $File.Save('c:\\Source\Output\Result.xml')

這是我的錯誤:

Cannot convert value "System.Object[]" to type "System.Xml.XmlDocument". Error: "The specified node cannot be inserted as the valid child of 
this node, because the specified node is the wrong type."
At line:9 char:10
+          $File =($meta.xml,[xml]$File.GetElementsByTagName("METATRANS ...
+          ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : MetadataError: (:) [], ArgumentTransformationMetadataException
    + FullyQualifiedErrorId : RuntimeException

非常感謝您的幫助。

從您之前的問題中,我了解到您從所有不需要的東西中刪除了大型 xml 文件,最終只得到METATRANSCRIPT:METATRANSCRIPT元素。

最重要的是,您要重新添加 XML 聲明。

由於您將 XML 文件視為純文本來執行剝離,因此您可以添加如下聲明:

Get-ChildItem -Path 'Path\To\XML\Files' -Filter '*.xml' -File | ForEach-Object {
    # do your routine on the xml in $_.FullName leaving only the METATRANSCRIPT element

    # if this leads to a string array in memory, just use that as-is
    $strippedXmlText = Strip-MyXml -Path $_.FullName

    # otherwise, if this leads to a temporary file, read it back in as string array:
    # $strippedXmlText = Get-Content -Path 'Path\To\The\Temp\File'

    $declaration = '<?xml version="1.0" encoding="UTF-8" standalone="yes"?>'
    # rewrite that file by prepending the declaration line to it
    Set-Content -Path 'Path\To\The\Output\File' -Value $declaration, $strippedXmlText -Encoding UTF8
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM