0

Is it possible to copy an element out of a xml with all parents?

Such as:

<root>
  <child>child1</child>
  <child>
    <subchild>subchild21</subchild>
  </child>
</root>

to:

<root><child><subchild>subchild21

or something equal?

Franz Ebner
  • 4,951
  • 3
  • 39
  • 57
  • why does it have to be notepad++ based? Do you have a scripting environment such as perl,php, python? Is a web-browser solution OK for you? – Lorenz Lo Sauer Sep 21 '12 at 07:12
  • it doesn't has to be notepad based... but it has to happen offline, I don't want to upload 100MB xmls – Franz Ebner Sep 21 '12 at 07:15
  • This may get you started https://gist.github.com/1297805 , and tangently related: http://stackoverflow.com/questions/8714090/queryselector-wildcard-element-match/10824813#10824813 – Lorenz Lo Sauer Sep 21 '12 at 07:22
  • i thought this would be a common usecase for a better editor.. seems not to be – Franz Ebner Sep 21 '12 at 07:26

3 Answers3

2

Put some id for that <subchild> and create new xml it will work

XDocument myXMLDocument = XDocument.Load("File.xml");
XElement mychildElement = myXMLDocument.Element("child");
XElement myFirstchildElement = mychildElement.Element("subchild");
XElement myNewchildElement = new XElement(myFirstchildElement);
XAttribute myChildId = myNewParentElement.Attribute("id");
mychild.Value = "subchild";
myFirstchileElement.AddAfterSelf(myNewchildElement);
myXMLDocument.Save("NewFile.xml");
Lorenz Lo Sauer
  • 23,698
  • 16
  • 85
  • 87
Parveen Sharief
  • 124
  • 1
  • 3
1

Just for future reference, you could achieve something similar with the DOM of the web-browser using:

var o = document.getElementsByTagName("subchild")[0];
var _xmlstr = o.innerText;
while( o ){
   _xmlstr = "<"+o.tagName.toLowerCase()+">"+_xmlstr; 
   o = o.parentNode;
};

Result:

<root><child><subchild>subchild21

Lorenz Lo Sauer
  • 23,698
  • 16
  • 85
  • 87
0

Notepad++ and XML Tools did it!

It's possible with

Ctrl + Alt + Shift + P

And called XPath

Franz Ebner
  • 4,951
  • 3
  • 39
  • 57
  • cheers! Be aware that [XPath](http://en.wikipedia.org/wiki/XPath) is a powerful W3C Schema/Standard with many implementations available. – Lorenz Lo Sauer Sep 21 '12 at 07:46
  • The shortcut, apparently copies the XPath of the currently selected node, or throws an ***unhandled exception*** in non-well formatted xml documents. NPP also has another Plugin called XPatherizerNPP. Note: Chrome's web-inspector allows right clicking on a node and selecting 'Copy XPath'. – Lorenz Lo Sauer Sep 21 '12 at 08:20
  • from my point of view, if the xml is not valid, it's more important to fix that instead of analyzing data from the xml itself... – Franz Ebner Sep 21 '12 at 09:26