Visual Basic 2013でXMLを操作 その2
新たにデータがXML形式で書かれているファイルを変更しなくてはならなくなったので、前回のソースコードをベースにして処理しました。
ajya.hatenablog.jp
変更前のXML形式のデータは以下のとおりです。
<?xml version="1.0" encoding="utf-8" standalone="yes"?> <Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships"> <Relationship Id="rId2" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/video" Target="../media/media1.avi" /> <Relationship Id="rId1" Type="http://schemas.microsoft.com/office/2007/relationships/media" Target="../media/media1.avi" /> </Relationships>
変更後のXML形式のデータは以下のとおりです。
<?xml version="1.0" encoding="utf-8" standalone="yes"?> <Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships"> <Relationship Id="rId2" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/video" Target="file:///C:\media\media1.avi" TargetMode="External" /> <Relationship Id="rId1" Type="http://schemas.microsoft.com/office/2007/relationships/media" Target="file:///C:\media\media1.avi" TargetMode="External" /> </Relationships>
変更しているのは、
Target="../media/media1.avi" ↓ Target="file:///C:\media\media1.avi"
の部分と、
TargetMode="External"
を追加している部分です。
以下のソースコードで、変更することができました。
'------------------------------- 'XMLを読み込む '------------------------------- Dim xml As XDocument xml = XDocument.Load("C:\Users\test\Desktop\now.xml") '名前空間を定義 Dim ns As XNamespace = "http://schemas.openxmlformats.org/package/2006/relationships" '処理したいツリーを選択 Dim resp = From num In xml.Root.Descendants(ns + "Relationship") Dim typeValue As String Dim targetValue As String For Each res In resp 'Type属性を取得 typeValue$ = res.Attribute("Type").Value.ToString If typeValue$ = "http://schemas.openxmlformats.org/officeDocument/2006/relationships/video" Or _ typeValue$ = "http://schemas.microsoft.com/office/2007/relationships/media" Then If (res.Attribute("TargetMode") Is Nothing) Then res.SetAttributeValue("TargetMode", "External") targetValue$ = targetValue.Replace("../media/", "file:///C:\media\") res.SetAttributeValue("Target", targetValue$) End If End If Next Dim xws As XmlWriterSettings = New XmlWriterSettings() xws.Encoding = New UTF8Encoding(False) Using xw = XmlWriter.Create("C:\Users\test\Desktop\new.xml", xws) xml.WriteTo(xw) End Using
- 前回と同様に、名前空間を扱っています。
- SetAttributeValue()でTargetMode="External"の追加を行えます。
- SetAttributeValue()で値の書き換えも行っています。