2017-09-01 46 views
2

我想從我的XML中刪除名爲<source file="..." />的特定元素,所以我可以比較它們。C#linq XML DeepCompare和標記刪除

<?xml version="1.0" encoding="utf-8"?> 
<!--XML document generated using OCR technology from Nuance Communications, Inc.--> 
<document xmlns="http://www.nuance.com/omnipage/xml/ssdoc-schema3.xsd" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> 
    <page ocr-vers="OmniPageCSDK16" app-vers="PaperVision Capture"> 
    <description backColor="d5d3d4"> 
     <source file="D:\Users\user\AppData\Roaming\OCR\\PVCPROCESSING_8\a9cfb6f2-b170-46f6-a00a-2f1557baee26.tmp" dpix="150" dpiy="150" sizex="1279" sizey="1652" /> 
     <theoreticalPage size="Letter" marginLeft="1700" marginTop="154" marginRight="739" marginBottom="3805" offsetX="-500" offsetY="-20" width="12240" height="15840" /> 
    </description> 

我試過這些方法無濟於事。它編譯好但沒有工作

doc1.Root.Element("document").Descendants().Where(e=>e.Name == "source").Remove(); 

doc1.Root.Element("document").Elements().Where(e=>e.Name == "source").Remove(); 

doc2.Root.Elements().Where(e=>e.Name == "source").Remove(); 

doc1.Descendants("document").Where(e=>e.Name == "source").Remove(); 

任何人都有任何線索,我做錯了什麼。

+0

你不使用的XNamespace'HTTP://www.nuance。 com/omnipage/xml/ssdoc-schema3.xsd' –

+0

是的,我正在保存它,我只是沒有在這裏發佈代碼。多數民衆贊成我如何知道該文件還沒有刪除的元素。 – Krom

+0

不使用xnamespace是什麼意思?我不能在這個時候更改xml中的內容,因爲有很多。 – Krom

回答

3

考慮到您不考慮xmlnamespace

看到這個簡單的例子

string xml1 = "<document> </document>"; 
var elem1 = XDocument.Parse(xml1).Element("document"); //elem1 contains document 

現在,插入一個命名空間http://aaa(如你的情況)

string xml2 = "<document xmlns=\"http://aaa\"> </document>"; 
var elem2 = XDocument.Parse(xml2).Element("document"); //elem2 is null 

elem2時現在是空的。

如何解決?使用的XNamespace

XNamespace ns = "http://aaa"; 
var elem3 = XDocument.Parse(xml2).Element(ns + "document"); //elem3 contains document 

最後,更復雜的例子(見XML命名空間的使用):

string xml4 = "<document xmlns=\"http://aaa\"> <subitem> <subsubitem> </subsubitem> </subitem> </document>"; 
XNamespace ns = "http://aaa"; 
var elems4 = XDocument.Parse(xml4).Element(ns + "document").Descendants(ns + "subsubitem") 
      .ToList(); 
+0

我相信我是用http:// aaa \替換命名空間與 「http://www.nuance.com/omnipage/xml/ssdoc-schema3.xsd」是否正確?我不確定第一個來自哪裏。 – Krom

+0

這也是返回對象不是對象'code'doc1.Element(「document」)。Element(「page」)。Element(「description」)。Element(「source」)。Remove();代碼' – Krom

+0

以外的命名空間問題是xdocument.parse會去忽略命名空間定義之前的xml版本和註釋嗎? @磅 – Krom