如何使用Powershell使用XmlUrlResolver读取包含字符实体的XML

时间:2015-02-25 20:10:42

标签: xml powershell xml-parsing dtd character-entities

使用以下Powershell行正常工作,直到它到达包含字符实体的XML文件:

$xml = [xml] (Get-Content $file.Name)

如何使用Powershell读取XML文件并让它解析DTD中的字符实体,而不是产生如下错误:

Cannot convert value "System.Object[]" to type "System.Xml.XmlDocument". Error: "Reference to undeclared entity 'nbsp'. Line 3, position 324."
Cannot convert value "System.Object[]" to type "System.Xml.XmlDocument". Error: "Reference to undeclared entity 'Oacute'. Line 3, position 239."

当XML文件有效且不包含字符实体时,它们很容易读取。我在XML文件中使用这些字符实体指定了DTD,但它没有使用它。 XML文件的示例启动:

<?xml version="1.0"?>
<!DOCTYPE catalog SYSTEM "manual.dtd">
<catalog ...

如何在Powershell中打开XML解析器? DTD文件与XML文件位于同一文件夹中。

我有在C#中绕过此问题的代码,但如何使用Powershell执行以下操作?

XML = XMLString;
var dtdPath = HttpContext.Current.ApplicationInstance.Server.MapPath("~/App_Data") + "\\Manual.dtd";
XML = XML.Replace("manual.dtd", dtdPath);
XmlUrlResolver resolver = new XmlUrlResolver();
resolver.Credentials = System.Net.CredentialCache.DefaultCredentials;
XmlReaderSettings settings = new XmlReaderSettings();
settings.DtdProcessing = DtdProcessing.Parse;
settings.ValidationType = ValidationType.None;
settings.XmlResolver = resolver;
XmlReader reader = XmlReader.Create(new System.IO.MemoryStream(System.Text.UTF8Encoding.UTF8.GetBytes(XML)), settings);
var XMLPrimary = XDocument.Load(reader);

这是我对Powershell代码的最佳猜测,但它仍然无效。如何使用Powershell设置XmlUrlResolver?

$resolver = New-Object -TypeName System.Xml.XmlUrlResolver
$resolver.Credentials = [System.Net.CredentialCache]::DefaultCredentials
$readerSettings = New-Object -TypeName System.Xml.XmlReaderSettings
$readerSettings.DtdProcessing = [System.Xml.DtdProcessing]::Parse
$readerSettings.ValidationType = [System.Xml.ValidationType]::DTD
$readerSettings.XmlResolver = $resolver
$readerSettings.MaxCharactersFromEntities = 2048;
$readerSettings.ValidationFlags = [System.Xml.Schema.XmlSchemaValidationFlags]::ProcessInlineSchema -bor [System.Xml.Schema.XmlSchemaValidationFlags]::ProcessSchemaLocation
$readerSettings.add_ValidationEventHandler(
{
    Write-Host $("`nError found in XML: " + $_.Message + "`n") -ForegroundColor Red
    $script:errorCount++
});
$reader = [System.Xml.XmlReader]::Create($XmlFile.FullName, $readerSettings)
while ($reader.Read()) { }
$reader.Close()

0 个答案:

没有答案