簡體   English   中英

從大型 XML 文件中選擇特定節點

[英]Selecting a specific node from a large XML file

(我正在使用 PowerShell 或 Z303CB0EF9EDB90972DAZ61 從大型 XML 文件中尋找 select 特定節點的方法和最佳方法)

下面顯示了我的 XML 文件的結構:

<?xml version="1.0" encoding="utf-8"?>
<T Id="XXXX" Date="20170102">
  <Node id="POS0030" nodeStatus="Online">
  <Node id="POS0031" nodeStatus="Online">
  <Node id="POS0032" nodeStatus="Online">
  <Node id="POS0033" nodeStatus="Online">
  <Node id="POS0034" nodeStatus="Online">
  <Node id="POS0035" nodeStatus="Online">
  <Node id="POS0036" nodeStatus="Online">
  <Node id="POS0049" nodeStatus="Online">
  <Node id="POS0050" nodeStatus="Online">
  <Node id="POS0097" nodeStatus="Online">
  <Node id="POS0098" nodeStatus="Online">
  <Node id="POS0099" nodeStatus="Online">
</T>

注意:每個節點下也有很多子節點

我想要做的是 select 特定的如 'POS0049' 並將文件保存到另一個位置。

謝謝,

我不知道是否有最有效的解決方案,但這項工作。

using System;
using System.Linq;
using System.Xml.Linq;

namespace ConsoleApp1
{
    class Program
    {
        static void Main(string[] args)
        {
            var xml = XElement.Load("SOURCEPATH");
            var idList = new string[] { "POS0001", "POS0002", "POS0032", "POS0033" };

            foreach (var node in (from n in xml.Elements("Node")
                                  where !idList.Contains(n.Attribute("id").Value)
                                  select n).ToArray())
                node.Remove();

            xml.Save("DESTINATIONPATH");
        }
    }
}

在 C# 中,您可以在 XmlDocument 中加載 xml。 搜索與您的 cirteria 匹配的所有節點並將它們添加到新的 XmlDocument。

該方法看起來像這樣

 static XmlDocument GetNodes(XmlDocument xmlDocument, string[] nodeIds)
        {
            var resultNodes = nodeIds.Select(x => xmlDocument.DocumentElement.SelectSingleNode($"Node[@id='{x}']")).ToList();

            XmlDocument resultDoc = new XmlDocument();
            resultDoc.AppendChild(resultDoc.ImportNode(xmlDocument.DocumentElement, false));
            foreach (var nd in resultNodes)
            {
                resultDoc.DocumentElement.AppendChild(resultDoc.ImportNode(nd, true));
            }
            return resultDoc;
        }

這是一個示例https://dotnetfiddle.net/Iy6hew

您的 XML 示例格式不正確,您應該使用 ="Online"/> 而不是 ="Online">

如果您的文件格式正確,您可以在 powershell 中進行:

[xml]$xmlfile=Get-Content "C:\temp\yourxmlfile.xml" -raw

$xmlfile.T.node | where {$_.id -notin ('POS0049', 'POS0050', 'POS0033', 'POS0034', 'POS0035', 'POS0036' )} |  %{$xmlfile.T.RemoveChild($_)}

$xmlfile.Save("c:\temp\yournewxmlfile.xml")

暫無
暫無

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

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