I recently created a post about flattening an XML structure so every element and it's values were turned into attributes on the root element. Got some great answer and got it working. However, sad thing is that by flattening, the client meant to flatten the elements and not make them into attributes :-/
What I have is this:
<members>
<member xmlns="mynamespace" id="1" status="1">
<sensitiveData>
<notes/>
<url>someurl</url>
<altUrl/>
<date1>somedate</date1>
<date2>someotherdate</date2>
<description>some description</description>
<tags/>
<category>some category</category>
</sensitiveData>
<contacts>
<contact contactId="1">
<contactPerson>some contact person</contactPerson>
<phone/>
<mobile>mobile number</mobile>
<email>some#email.com</email>
</contact>
</kontakter>
</member>
</members>
And what I need is the following:
<members>
<member xmlns="mynamespace" id="1" status="1">
<sensitiveData/>
<notes/>
<url>someurl</url>
<altUrl/>
<date1>somedate</date1>
<date2>someotherdate</date2>
<description>some description</description>
<tags/>
<category>some category</category>
<contacts/>
<contact contactId="1"></contact>
<contactPerson>some contact person</contactPerson>
<phone/>
<mobile>mobile number</mobile>
<email>some#email.com</email>
</member>
</members>
So basically all elements, but flattened as childnodes of . I do know that it's not pretty at all to begin parsing XML documents like this, but it's basically the only option left as the CMS we're importing data to requires this flat structure and the XML document comes from an external webservice.
I started to make a recursive method for this, but I've got an odd feeling that it could be made smoother (well, as smooth as possible at least) with some LINQ to XML (?) I'm not the best at linq to xml, so I hope there's someone out there who would be helpful to give a hint on how to solve this? :-)
This seems to work - there may be neater approaches, admittedly:
var doc = XDocument.Load("test.xml");
XNamespace ns = "mynamespace";
var member = doc.Root.Element(ns + "member");
// This will *sort* of flatten, but create copies...
var descendants = member.Descendants().ToList();
// So we need to strip child elements from everywhere...
// (but only elements, not text nodes). The ToList() call
// materializes the query, so we're not removing while we're iterating.
foreach (var nested in descendants.Elements().ToList())
{
nested.Remove();
}
member.ReplaceNodes(descendants);
Related
I have xml structure as below. How can I replace the element value of that is present everywhere in this structure? Is there a way to do this using Linq? Also, sometimes the structure could be different but there will always be Resource element so I need to look at all instances of Resource and not care about where it is present.
Thanks for any suggestions.
<Users>
<User>
<Number>123456</Number>
<ID>1</ID>
<Events>
<Event>
<ID>12</ID>
</Event>
</Events>
<Items>
<Item>
<ID>12</ID>
<Resource>Replace this value</Resource>
</Item>
<Item>
<ID>13</ID>
<Resource>Replace this value</Resource>
</Item>
<Item>
<ID>14</ID>
<Resource>Replace this value</Resource>
</Item>
</Items>
</User>
//More User elements where Resource needs to be updated
<User>
</User>
<User>
</User>
</Users>
Linq is a query language, so you can't directly use it to modify the value, but you can easily select all the Resource elements in the document with it and iterate/change them.
For example:
// or load from xml, however you have it
var xDoc = XDocument.Load(#"c:\temp\myxml.xml");
// iterate every Resource element
foreach (XElement element in xDoc.Descendants("Resource"))
element.Value = "Hello, world";
That will pick out every Resource element in the XML regardless of where it is in the hierarchy, which in your case, is what you need. If you needed to target it more specifically, you could either use an XPath expression or further Linq calls such as Element() which work on a single level of the hierarchy.
I'm wondering if there is a way to do the following with one xpath expression:
I have an XML doc similar to this but with many 'results',
<result>
<id>1</id>
<name>joe</name>
</result>
<result>
<id>2</id>
<name>jim</name>
</result>
I'm passing a variable into a C# utility along with the xml, and want to return the name where the id = the variable.
I could loop through the xml until reach what I'm after but if there's a handy xpath way to do it I'm listening...
thanks
Assuming you have a root element in there like "results" that XPath can validate, and that you don't have any other nodes named "result"...
//result[id=1]/name
Or you could get the text outright, instead of it being returned in a node
//result[id=1]/name/text()
And if you want to make sure that there's only one result, you could surround it with parens and put a [1] after
(//result[id=1]/name/text())[1]
I would also recommend testing with one of the xpath test sites out there like this one, but beware that different xpath/xml parsers sometimes behave differently.
so I have a massive XML file that contains a structure similar to this one:
<Item ItemId=";ResTVersion" ItemType="0" PsrId="245" Leaf="false">
<Disp Icon="Str" Expand="true" Disp="true" LocTbl="false" Order="13352" />
<Modified By="sachink" DateTime="2008-12-16T19:02:35Z" />
<PsrProps>
<Str Name="Kii" Val="yyyyyyyyyyyyy" />
</PsrProps>
<Item ItemId=";ResTFileVersion" ItemType="0;ResT" PsrId="245" InstFlg="true" Leaf="true">
<Str Cat="Text" UsrLk="true">
<Val><![CDATA[ttttttttt]]></Val>
<Tgt Cat="Text" Orig="New">
<Val><![CDATA[ttttttttt]]></Val>
</Tgt>
</Str>
<Disp Icon="Str" Order="13353" />
<Modified By="sachink" DateTime="2008-12-16T19:02:35Z" />
<Cmts>
<Cmt Name="Dev"><![CDATA[{Locked}]]></Cmt>
</Cmts>
</Item>
<Item ItemId=";ResTLanguageTag" ItemType="0;ResT" PsrId="245" InstFlg="true" Leaf="true">
<Str Cat="Text" UsrLk="true">
<Val><![CDATA[en-US]]></Val>
<Tgt Cat="Text" Orig="New">
<Val><![CDATA[en-US]]></Val>
</Tgt>
</Str>
<Disp Icon="Str" Order="13354" />
<Modified By="sachink" DateTime="2008-12-16T19:02:35Z" />
<Cmts>
<Cmt Name="Dev"><![CDATA[=.ABVUDHUIDSHFUIDSHFUISHDFUIDSH iusdhfUIHAs]]></Cmt>
</Cmts>
</Item>
</Item>
I have several item ids and I want to create a new xml that respects the old structure.
I use this code to retrieve the nodes that I want, and then create the new XML.
XmlNodeList nodes = originalXML.SelectNodes("//*[contains(#ItemId,'" + id + "')]");
So what I want is to remove some nodes but I only have the ids of the ones I want to keep.
The problem is how do you keep the outer structure of an xml, when you use the selectnodes function, to get the inner nodes?
Thanks!
I would go the opposite way: remove what you don't need. It's hard to build an XmlDocument from scratch (takes a lot of coding).
I think you will be better off removing the nodes you don't want from the structure you already have.
XmlNodeList nodes = originalXML.SelectNodes("/*[not(contains(#test,'test'))]")
foreach(XmlNode node in nodes)
originalXML.RemoveChild(node);
should work.
If you need to preserve your original structure you can originalXML.Clone() it.
Sidenote: You might want to look into System.Xml.Linq.XDocument and System.Xml.Linq.XElement I find those a lot easier to use.
I have an XML format of this structure (the real world example is horrendously long and complicated, but this should illustrate it):
<document> <post>
<author>Bill Smith</author>
<subject>Test Article</subject>
<dates>
<uploaded>some date</uploaded>
<published>some date</published>
</dates>
</post>
<post>
<author>Bill Smith</author>
<subject>Test Article</subject>
<dates>
<uploaded>some date</uploaded>
<published>some date</published>
</dates>
</post> </document>
I have wrote a simple query to pull out each of the posts. I can get the author and subject fine, but I don't know how to drill down into the dates part to pull out the published bit.
Thanks
You can use the following LINQ to get the first "published" element.
XDocument document = XDocument.Load(#"D:\XMLFile1.xml", LoadOptions.None);
XElement element = document
.Descendants("document")
.Descendants("post")
.Descendants("dates")
.Descendants("published")
.First();
string publishedDate = element.Value;
You can give any expressions as parameter to the 'Descendants' method.
If you have xml as a string, you can use the following to read it into an XDocument
XDocument.Parse();
Please remember to check for nulls!! :-)
I am working on a biztalk project and I need to copy (filtered) content from 1 xml to another.
I have to do this with xpath, I can't use xsl transformation.
So my xpath to get the content from the source xml file is this:
//*[not(ancestor-or-self::IN1_Insurance)]|//IN1_Insurance[2]/descendant-or-self::*
Now this returns an xmlNodelist. Is it possible to return a string with all the nodes in it like:
"<root><node>text</node></root>"
If I put string() before my xpath it returns the values, but I want the whole xml in a string (with nodes..), so I could load that string in another xmldocument. I think this is the best method for my problem.
I know I can loop over the xmlnodelist and append the nodes to the new xmldocument, but it's a bit tricky to loop in a biztalk orchestration and I want to avoid this.
The code I can use is C#.
I've tried to just assign the nodelist to the xmldocument, but this throws a cast error (obvious..).
The way I see it is that I have 2 solutions:
assign the nodelist to the xmldocument without a loop (not possible i think in C#)
somehow convert the nodelist to string and load this in the xmldocument
load the xpath directly in the new xmldocument (don't know if this is possible since it returns a nodelist)
Thanks for your help
edit:
sample input:
<root>
<Patient>
<PatientId></PatientId>
<name></name>
</Patient>
<insurance>
<id>1</id>
<billing></billing>
</insurance
<insurance>
<id>2</id>
<billing></billing>
</insurance>
<insurance>
<id>3</id>
<billing></billing>
</insurance>
</root>
Now I want to copy this sample to another xmldocument, but without insurance node 2 and 3 (this is dynamically, so it could be unsurance node 1 and 2 to delete, or 1 and 3...)
So this has to be the output:
<root>
<Patient>
<PatientId></PatientId>
<name></name>
</Patient>
<insurance>
<id>1</id>
<billing></billing>
</insurance>
</root>
What I am doing now is use the xpath to get the nodes I want. Then I want to assign the result to the new xmldocument, but this is not possible since I get the castException
string xpath = "//*[not(ancestor-or-self::IN1_Insurance)]|//IN1_Insurance[2]/descendant-or-self::*";
xmlDoc = new System.Xml.XmlDocument();
xmlDoc = xpath(sourceXml, strXpath); <= cast error (cannot cast xmlnodelist to xmldocuemnt)
I know the syntax is a bit strange, but it is biztalk c# code..
The most straightforward solution would indeed be to "loop over the xmlnodelist and append (import) the nodes to the new xmldocument", but since you can't loop, what other basic things can/can't you do?
To serialize the nodelist, you could try using XmlNodeList.toString(). If that worked, you'd get a strange beast, because it could be duplicating parts of the XML document several times over. Especially since you're explicitly including ancestors and descendants directly in the nodelist. It would not be something that you could parse back in and have a result that resembled the nodelist you started with.
In other words, it would be best to loop over the XmlNodeList and import the nodes to the new XmlDocument.
But even so, I would be really surprised if you wanted to put all these ancestor and descendant nodes:
//*[not(ancestor-or-self::IN1_Insurance)]|//IN1_Insurance[2]/descendant-or-self::
directly into the new XML document. If you post some sample input and the desired output, we can probably help determine if that's the case.
Update:
I see what you're trying to do: copy an XML document, omitting all <insurance> elements (and their descendants) except the one you want.
This can be done without a loop if the output is as simple as your sample output: only one <Patient> and one <insurance> element, with their descendants, under one top-level element.
Something like (I can't test this as I don't have a biztalk server):
string xpathPatient = "/*/Patient";
string xpathInsuran = "/*/insurance[id = " + insId + "]"; // insId is a parameter
xmlDoc = new System.Xml.XmlDocument();
xmlPatient = xpath(sourceXml, xpathPatient);
xmlInsuran = xpath(sourceXml, xpathInsuran);
XmlElement rootNode = xmlDoc.CreateElement("root");
xmlDoc.AppendChild(rootNode);
//**Update: use [0] to get an XmlNode from the returned XmlNodeList (presumably)
rootNode.AppendChild(xmlDoc.ImportNode(xmlPatient[0], true));
rootNode.AppendChild(xmlDoc.ImportNode(xmlInsuran[0], true));
I confess though, I'm curious why you can't use XSLT. You're approaching tasks that would be more easily done in XSLT than in XPath + C# XmlDocument.
Update: since the xpath() function probably returns an XmlNodeList rather than an XmlNode, I added [0] to the first argument to ImportNode() above. Thanks to #Martin Honnen for alerting me to that.
XPath is a query language (only) for XML documents.
It operates on an abstract model -- the XML INFOSET, and cannot either modify the structure of the XML document(s) it operates on or serialize the INFOSET information items back to XML.
Therefore, the only way to achieve such serialization is to use the language that is hosting XPath.
Apart from this, there are obvious problems with yout question, for example these is no element named IN1_Insurance in the provided XML document -- therefore the XPath expression provided:
//*[not(ancestor-or-self::IN1_Insurance)]|//IN1_Insurance[2]/descendant-or-self::*
selects all elements in the document.
Note:
The described task is elementary to fulfil using XSLT.
Finally: If you are allowed to use C# then you can use the XslCompiledTransform (or XslTransform) class. Use its Transform() method to carry out the following transformation against the XML document:
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output omit-xml-declaration="yes" indent="yes"/>
<xsl:strip-space elements="*"/>
<xsl:template match="node()|#*">
<xsl:copy>
<xsl:apply-templates select="node()|#*"/>
</xsl:copy>
</xsl:template>
<xsl:template match="insurance[not(id=1)]"/>
</xsl:stylesheet>
This produces exactly the wanted result:
<root>
<Patient>
<PatientId></PatientId>
<name></name>
</Patient>
<insurance>
<id>1</id>
<billing></billing>
</insurance>
</root>