Python read all elements in XAML file and replace some valuesFind replace Element using PythonReplacements for switch statement in Python?How do I copy a file in Python?Getting the last element of a listHow do I get the number of elements in a list?open() in Python does not create a file if it doesn't existHow do I list all files of a directory?How to read a file line-by-line into a list?Find all files in a directory with extension .txt in PythonHow do you append to a file in Python?Why is reading lines from stdin much slower in C++ than Python?
Why does the standard fingering / strumming for a D maj chord leave out the 5th string?
What are these funnel-looking green things in my yard?
Does fossil fuels use since 1990 account for half of all the fossil fuels used in history?
The cat ate your input again!
How is являться different from есть and быть
What kind of liquid can be seen 'leaking' from the upper surface of the wing of a Boeing 737-800?
Word for an event that will likely never happen again
How to take the beginning and end parts of a list with simpler syntax?
Can you end your own spell prematurely?
First amendment and employment: Can a police department terminate an officer for speech?
What can Amex do if I cancel their card after using the sign up bonus miles?
Do I have to cite common CS algorithms?
Boss wants me to ignore a software API license prohibiting mass download
Why is the result of ('b'+'a'+ + 'a' + 'a').toLowerCase() 'banana'?
Why is there a large performance impact when looping over an array over 240 elements?
Website error: "Walmart can’t use this browser"
Regex crossword (sudoku?)
How far did Gandalf and the Balrog drop from the bridge in Moria?
Is there a way to count the number of lines of text in a file including non-delimited ones?
Markov-chain sentence generator in Python
My cat is a houdini
How many British prisoners of war were taken by the Wehrmacht and how many died?
If clocks themselves are based on light signals, wouldn't we expect the measured speed of light to always be the same constant?
Is this n-speak?
Python read all elements in XAML file and replace some values
Find replace Element using PythonReplacements for switch statement in Python?How do I copy a file in Python?Getting the last element of a listHow do I get the number of elements in a list?open() in Python does not create a file if it doesn't existHow do I list all files of a directory?How to read a file line-by-line into a list?Find all files in a directory with extension .txt in PythonHow do you append to a file in Python?Why is reading lines from stdin much slower in C++ than Python?
.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty margin-bottom:0;
So i have XML file, inside the file i have many elements like this:
<name search = "read TTT: write">
<version id = "1.0.0">
<value>myVal</value>
<method>myMethod</method>
</version>
</name>
So in each element i need to find this search = "read TTT: write" line and in case this read TTT: write start with read i need to change it (replace the read with another string).
What is the bestfastest way to do that ?
Update
So in case i have element like this (the word 'read' exist):
<name search = "read TTT: write">
<version id = "1.0.0">
<value>myVal</value>
<method>myMethod</method>
</version>
</name>
I want to replace it with this one (i only replace the read):
<name search = "NewValue TTT: write">
<version id = "1.0.0">
<value>myVal</value>
<method>myMethod</method>
</version>
</name>
python xml
|
show 1 more comment
So i have XML file, inside the file i have many elements like this:
<name search = "read TTT: write">
<version id = "1.0.0">
<value>myVal</value>
<method>myMethod</method>
</version>
</name>
So in each element i need to find this search = "read TTT: write" line and in case this read TTT: write start with read i need to change it (replace the read with another string).
What is the bestfastest way to do that ?
Update
So in case i have element like this (the word 'read' exist):
<name search = "read TTT: write">
<version id = "1.0.0">
<value>myVal</value>
<method>myMethod</method>
</version>
</name>
I want to replace it with this one (i only replace the read):
<name search = "NewValue TTT: write">
<version id = "1.0.0">
<value>myVal</value>
<method>myMethod</method>
</version>
</name>
python xml
Possible duplicate of Find replace Element using Python
– Nenri
Mar 27 at 10:18
The string you want to replace with is always the same?
– Alderven
Mar 27 at 10:19
user @Alderven : no, this line: read TTT: write start here with read, so all the elements that name start with read i want to replace
– falukky
Mar 27 at 10:21
Could you please add expected XML sample?
– Alderven
Mar 27 at 10:23
please see my update
– falukky
Mar 27 at 10:27
|
show 1 more comment
So i have XML file, inside the file i have many elements like this:
<name search = "read TTT: write">
<version id = "1.0.0">
<value>myVal</value>
<method>myMethod</method>
</version>
</name>
So in each element i need to find this search = "read TTT: write" line and in case this read TTT: write start with read i need to change it (replace the read with another string).
What is the bestfastest way to do that ?
Update
So in case i have element like this (the word 'read' exist):
<name search = "read TTT: write">
<version id = "1.0.0">
<value>myVal</value>
<method>myMethod</method>
</version>
</name>
I want to replace it with this one (i only replace the read):
<name search = "NewValue TTT: write">
<version id = "1.0.0">
<value>myVal</value>
<method>myMethod</method>
</version>
</name>
python xml
So i have XML file, inside the file i have many elements like this:
<name search = "read TTT: write">
<version id = "1.0.0">
<value>myVal</value>
<method>myMethod</method>
</version>
</name>
So in each element i need to find this search = "read TTT: write" line and in case this read TTT: write start with read i need to change it (replace the read with another string).
What is the bestfastest way to do that ?
Update
So in case i have element like this (the word 'read' exist):
<name search = "read TTT: write">
<version id = "1.0.0">
<value>myVal</value>
<method>myMethod</method>
</version>
</name>
I want to replace it with this one (i only replace the read):
<name search = "NewValue TTT: write">
<version id = "1.0.0">
<value>myVal</value>
<method>myMethod</method>
</version>
</name>
python xml
python xml
edited Mar 27 at 10:25
falukky
asked Mar 27 at 10:15
falukkyfalukky
4781 gold badge4 silver badges13 bronze badges
4781 gold badge4 silver badges13 bronze badges
Possible duplicate of Find replace Element using Python
– Nenri
Mar 27 at 10:18
The string you want to replace with is always the same?
– Alderven
Mar 27 at 10:19
user @Alderven : no, this line: read TTT: write start here with read, so all the elements that name start with read i want to replace
– falukky
Mar 27 at 10:21
Could you please add expected XML sample?
– Alderven
Mar 27 at 10:23
please see my update
– falukky
Mar 27 at 10:27
|
show 1 more comment
Possible duplicate of Find replace Element using Python
– Nenri
Mar 27 at 10:18
The string you want to replace with is always the same?
– Alderven
Mar 27 at 10:19
user @Alderven : no, this line: read TTT: write start here with read, so all the elements that name start with read i want to replace
– falukky
Mar 27 at 10:21
Could you please add expected XML sample?
– Alderven
Mar 27 at 10:23
please see my update
– falukky
Mar 27 at 10:27
Possible duplicate of Find replace Element using Python
– Nenri
Mar 27 at 10:18
Possible duplicate of Find replace Element using Python
– Nenri
Mar 27 at 10:18
The string you want to replace with is always the same?
– Alderven
Mar 27 at 10:19
The string you want to replace with is always the same?
– Alderven
Mar 27 at 10:19
user @Alderven : no, this line: read TTT: write start here with read, so all the elements that name start with read i want to replace
– falukky
Mar 27 at 10:21
user @Alderven : no, this line: read TTT: write start here with read, so all the elements that name start with read i want to replace
– falukky
Mar 27 at 10:21
Could you please add expected XML sample?
– Alderven
Mar 27 at 10:23
Could you please add expected XML sample?
– Alderven
Mar 27 at 10:23
please see my update
– falukky
Mar 27 at 10:27
please see my update
– falukky
Mar 27 at 10:27
|
show 1 more comment
3 Answers
3
active
oldest
votes
Using minidom:
from xml.dom import minidom
xmldoc = minidom.parseString(xml)
tags = xmldoc.getElementsByTagName("name")
firstchild = tags[0]
firstchild.attributes["search"].value = 'NewValue TTT: write'
print(xmldoc.toxml())
OUTPUT:
<?xml version="1.0" ?><name search="NewValue TTT: write">
<version id="1.0.0">
<value>myVal</value>
<method>myMethod</method>
</version>
</name>
EDIT:
For multiple tags, simply loop over:
xml = '''
<root>
<name search = "read TTT: write">
<version id = "1.0.0">
<value>myVal</value>
<method>myMethod</method>
</version>
</name>
<name search = "read2 TTT: write">
<version id = "2.0.0">
<value>myVal_2</value>
<method>myMethod_2</method>
</version>
</name>
</root>'''
from xml.dom import minidom
xmldoc = minidom.parseString(xml)
tags = xmldoc.getElementsByTagName("name")
for item in tags:
item.attributes["search"].value = 'NewValue TTT: write'
print(xmldoc.toxml())
OUTPUT:
<?xml version="1.0" ?><root>
<name search="NewValue TTT: write">
<version id="1.0.0">
<value>myVal</value>
<method>myMethod</method>
</version>
</name>
<name search="NewValue TTT: write">
<version id="2.0.0">
<value>myVal_2</value>
<method>myMethod_2</method>
</version>
</name>
</root>
Using beautifulsoup:
from bs4 import BeautifulSoup
xml = '''
<root>
<name search = "read TTT: write">
<version id = "1.0.0">
<value>myVal</value>
<method>myMethod</method>
</version>
</name>
<name search = "read TTT: write">
<version id = "2.0.0">
<value>myVal_2</value>
<method>myMethod_2</method>
</version>
</name>
</root>'''
soup = BeautifulSoup(xml , 'lxml')
newVal = "NewValue"
for elem in soup.find_all("name"):
elem['search'] = elem['search'].replace(str(elem['search']).split(" ")[0], newVal)
print(elem)
OUTPUT:
<name search="NewValue TTT: write">
<version id="1.0.0">
<value>myVal</value>
<method>myMethod</method>
</version>
</name>
<name search="NewValue TTT: write">
<version id="2.0.0">
<value>myVal_2</value>
<method>myMethod_2</method>
</version>
</name>
Thats works but, any way to add this new name elements to the xml file instead of edit the old ones ? (keep the old and add the new)
– falukky
Mar 27 at 12:58
@falukky ofcourse create a new dom element or an empty xml file using beautiful soup and append these to it. This will go outside the current asked question. I suggest you ask a new question with your attempts shown. PS. If this answer helped you may accept it. Cheers! :)
– DirtyBit
Mar 27 at 13:06
add a comment |
from xml.dom.minidom import parse #minidom does the trick
dom = parse('my_file.xml') #read in your file
res = dom.getElementsByTagName('name') #fetch the desired elements in the tree
for element in res: #loop through all
if element.getAttribute('search') == 'read TTT: write': #filter for the attribute and value
element.setAttribute('search', 'New Value TTT: write') #in case of match, replace
with open('my_file_updated.xml','w') as f: #store the file
f.write(dom.toxml())
Thanks, any way to add this new name elements to the xml file instead of edit the old ones ?
– falukky
Mar 27 at 12:00
add a comment |
Try This:
xml = """<?xml version="1.0" encoding="UTF-8"?>
<body>
<name search = "read TTT: write">
<version id = "1.0.0">
<value>myVal</value>
<method>myMethod</method>
</version>
</name>
<name search = "read TTT: write">
<version id = "1.0.0">
<value>myVal</value>
<method>myMethod</method>
</version>
</name>
</body>
"""
import xml.etree.ElementTree as ET
tree = ET.fromstring(xml)
sh = tree.findall('name')
for name in sh:
val = name.get("search")
if str(val) == "read TTT: write":
name.set('search', 'NewValue TTT: write')
print (ET.tostring(tree))
Output:
<body>
<name search = "NewValue TTT: write">
<version id = "1.0.0">
<value>myVal</value>
<method>myMethod</method>
</version>
</name>
<name search = "NewValue TTT: write">
<version id = "1.0.0">
<value>myVal</value>
<method>myMethod</method>
</version>
</name>
</body>
This print only the first name element and my XML have mane name elements
– falukky
Mar 27 at 11:06
@falukky :Try the Updated code
– Suraj M
Mar 27 at 11:16
add a comment |
Your Answer
StackExchange.ifUsing("editor", function ()
StackExchange.using("externalEditor", function ()
StackExchange.using("snippets", function ()
StackExchange.snippets.init();
);
);
, "code-snippets");
StackExchange.ready(function()
var channelOptions =
tags: "".split(" "),
id: "1"
;
initTagRenderer("".split(" "), "".split(" "), channelOptions);
StackExchange.using("externalEditor", function()
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled)
StackExchange.using("snippets", function()
createEditor();
);
else
createEditor();
);
function createEditor()
StackExchange.prepareEditor(
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader:
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
,
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
);
);
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55374724%2fpython-read-all-elements-in-xaml-file-and-replace-some-values%23new-answer', 'question_page');
);
Post as a guest
Required, but never shown
3 Answers
3
active
oldest
votes
3 Answers
3
active
oldest
votes
active
oldest
votes
active
oldest
votes
Using minidom:
from xml.dom import minidom
xmldoc = minidom.parseString(xml)
tags = xmldoc.getElementsByTagName("name")
firstchild = tags[0]
firstchild.attributes["search"].value = 'NewValue TTT: write'
print(xmldoc.toxml())
OUTPUT:
<?xml version="1.0" ?><name search="NewValue TTT: write">
<version id="1.0.0">
<value>myVal</value>
<method>myMethod</method>
</version>
</name>
EDIT:
For multiple tags, simply loop over:
xml = '''
<root>
<name search = "read TTT: write">
<version id = "1.0.0">
<value>myVal</value>
<method>myMethod</method>
</version>
</name>
<name search = "read2 TTT: write">
<version id = "2.0.0">
<value>myVal_2</value>
<method>myMethod_2</method>
</version>
</name>
</root>'''
from xml.dom import minidom
xmldoc = minidom.parseString(xml)
tags = xmldoc.getElementsByTagName("name")
for item in tags:
item.attributes["search"].value = 'NewValue TTT: write'
print(xmldoc.toxml())
OUTPUT:
<?xml version="1.0" ?><root>
<name search="NewValue TTT: write">
<version id="1.0.0">
<value>myVal</value>
<method>myMethod</method>
</version>
</name>
<name search="NewValue TTT: write">
<version id="2.0.0">
<value>myVal_2</value>
<method>myMethod_2</method>
</version>
</name>
</root>
Using beautifulsoup:
from bs4 import BeautifulSoup
xml = '''
<root>
<name search = "read TTT: write">
<version id = "1.0.0">
<value>myVal</value>
<method>myMethod</method>
</version>
</name>
<name search = "read TTT: write">
<version id = "2.0.0">
<value>myVal_2</value>
<method>myMethod_2</method>
</version>
</name>
</root>'''
soup = BeautifulSoup(xml , 'lxml')
newVal = "NewValue"
for elem in soup.find_all("name"):
elem['search'] = elem['search'].replace(str(elem['search']).split(" ")[0], newVal)
print(elem)
OUTPUT:
<name search="NewValue TTT: write">
<version id="1.0.0">
<value>myVal</value>
<method>myMethod</method>
</version>
</name>
<name search="NewValue TTT: write">
<version id="2.0.0">
<value>myVal_2</value>
<method>myMethod_2</method>
</version>
</name>
Thats works but, any way to add this new name elements to the xml file instead of edit the old ones ? (keep the old and add the new)
– falukky
Mar 27 at 12:58
@falukky ofcourse create a new dom element or an empty xml file using beautiful soup and append these to it. This will go outside the current asked question. I suggest you ask a new question with your attempts shown. PS. If this answer helped you may accept it. Cheers! :)
– DirtyBit
Mar 27 at 13:06
add a comment |
Using minidom:
from xml.dom import minidom
xmldoc = minidom.parseString(xml)
tags = xmldoc.getElementsByTagName("name")
firstchild = tags[0]
firstchild.attributes["search"].value = 'NewValue TTT: write'
print(xmldoc.toxml())
OUTPUT:
<?xml version="1.0" ?><name search="NewValue TTT: write">
<version id="1.0.0">
<value>myVal</value>
<method>myMethod</method>
</version>
</name>
EDIT:
For multiple tags, simply loop over:
xml = '''
<root>
<name search = "read TTT: write">
<version id = "1.0.0">
<value>myVal</value>
<method>myMethod</method>
</version>
</name>
<name search = "read2 TTT: write">
<version id = "2.0.0">
<value>myVal_2</value>
<method>myMethod_2</method>
</version>
</name>
</root>'''
from xml.dom import minidom
xmldoc = minidom.parseString(xml)
tags = xmldoc.getElementsByTagName("name")
for item in tags:
item.attributes["search"].value = 'NewValue TTT: write'
print(xmldoc.toxml())
OUTPUT:
<?xml version="1.0" ?><root>
<name search="NewValue TTT: write">
<version id="1.0.0">
<value>myVal</value>
<method>myMethod</method>
</version>
</name>
<name search="NewValue TTT: write">
<version id="2.0.0">
<value>myVal_2</value>
<method>myMethod_2</method>
</version>
</name>
</root>
Using beautifulsoup:
from bs4 import BeautifulSoup
xml = '''
<root>
<name search = "read TTT: write">
<version id = "1.0.0">
<value>myVal</value>
<method>myMethod</method>
</version>
</name>
<name search = "read TTT: write">
<version id = "2.0.0">
<value>myVal_2</value>
<method>myMethod_2</method>
</version>
</name>
</root>'''
soup = BeautifulSoup(xml , 'lxml')
newVal = "NewValue"
for elem in soup.find_all("name"):
elem['search'] = elem['search'].replace(str(elem['search']).split(" ")[0], newVal)
print(elem)
OUTPUT:
<name search="NewValue TTT: write">
<version id="1.0.0">
<value>myVal</value>
<method>myMethod</method>
</version>
</name>
<name search="NewValue TTT: write">
<version id="2.0.0">
<value>myVal_2</value>
<method>myMethod_2</method>
</version>
</name>
Thats works but, any way to add this new name elements to the xml file instead of edit the old ones ? (keep the old and add the new)
– falukky
Mar 27 at 12:58
@falukky ofcourse create a new dom element or an empty xml file using beautiful soup and append these to it. This will go outside the current asked question. I suggest you ask a new question with your attempts shown. PS. If this answer helped you may accept it. Cheers! :)
– DirtyBit
Mar 27 at 13:06
add a comment |
Using minidom:
from xml.dom import minidom
xmldoc = minidom.parseString(xml)
tags = xmldoc.getElementsByTagName("name")
firstchild = tags[0]
firstchild.attributes["search"].value = 'NewValue TTT: write'
print(xmldoc.toxml())
OUTPUT:
<?xml version="1.0" ?><name search="NewValue TTT: write">
<version id="1.0.0">
<value>myVal</value>
<method>myMethod</method>
</version>
</name>
EDIT:
For multiple tags, simply loop over:
xml = '''
<root>
<name search = "read TTT: write">
<version id = "1.0.0">
<value>myVal</value>
<method>myMethod</method>
</version>
</name>
<name search = "read2 TTT: write">
<version id = "2.0.0">
<value>myVal_2</value>
<method>myMethod_2</method>
</version>
</name>
</root>'''
from xml.dom import minidom
xmldoc = minidom.parseString(xml)
tags = xmldoc.getElementsByTagName("name")
for item in tags:
item.attributes["search"].value = 'NewValue TTT: write'
print(xmldoc.toxml())
OUTPUT:
<?xml version="1.0" ?><root>
<name search="NewValue TTT: write">
<version id="1.0.0">
<value>myVal</value>
<method>myMethod</method>
</version>
</name>
<name search="NewValue TTT: write">
<version id="2.0.0">
<value>myVal_2</value>
<method>myMethod_2</method>
</version>
</name>
</root>
Using beautifulsoup:
from bs4 import BeautifulSoup
xml = '''
<root>
<name search = "read TTT: write">
<version id = "1.0.0">
<value>myVal</value>
<method>myMethod</method>
</version>
</name>
<name search = "read TTT: write">
<version id = "2.0.0">
<value>myVal_2</value>
<method>myMethod_2</method>
</version>
</name>
</root>'''
soup = BeautifulSoup(xml , 'lxml')
newVal = "NewValue"
for elem in soup.find_all("name"):
elem['search'] = elem['search'].replace(str(elem['search']).split(" ")[0], newVal)
print(elem)
OUTPUT:
<name search="NewValue TTT: write">
<version id="1.0.0">
<value>myVal</value>
<method>myMethod</method>
</version>
</name>
<name search="NewValue TTT: write">
<version id="2.0.0">
<value>myVal_2</value>
<method>myMethod_2</method>
</version>
</name>
Using minidom:
from xml.dom import minidom
xmldoc = minidom.parseString(xml)
tags = xmldoc.getElementsByTagName("name")
firstchild = tags[0]
firstchild.attributes["search"].value = 'NewValue TTT: write'
print(xmldoc.toxml())
OUTPUT:
<?xml version="1.0" ?><name search="NewValue TTT: write">
<version id="1.0.0">
<value>myVal</value>
<method>myMethod</method>
</version>
</name>
EDIT:
For multiple tags, simply loop over:
xml = '''
<root>
<name search = "read TTT: write">
<version id = "1.0.0">
<value>myVal</value>
<method>myMethod</method>
</version>
</name>
<name search = "read2 TTT: write">
<version id = "2.0.0">
<value>myVal_2</value>
<method>myMethod_2</method>
</version>
</name>
</root>'''
from xml.dom import minidom
xmldoc = minidom.parseString(xml)
tags = xmldoc.getElementsByTagName("name")
for item in tags:
item.attributes["search"].value = 'NewValue TTT: write'
print(xmldoc.toxml())
OUTPUT:
<?xml version="1.0" ?><root>
<name search="NewValue TTT: write">
<version id="1.0.0">
<value>myVal</value>
<method>myMethod</method>
</version>
</name>
<name search="NewValue TTT: write">
<version id="2.0.0">
<value>myVal_2</value>
<method>myMethod_2</method>
</version>
</name>
</root>
Using beautifulsoup:
from bs4 import BeautifulSoup
xml = '''
<root>
<name search = "read TTT: write">
<version id = "1.0.0">
<value>myVal</value>
<method>myMethod</method>
</version>
</name>
<name search = "read TTT: write">
<version id = "2.0.0">
<value>myVal_2</value>
<method>myMethod_2</method>
</version>
</name>
</root>'''
soup = BeautifulSoup(xml , 'lxml')
newVal = "NewValue"
for elem in soup.find_all("name"):
elem['search'] = elem['search'].replace(str(elem['search']).split(" ")[0], newVal)
print(elem)
OUTPUT:
<name search="NewValue TTT: write">
<version id="1.0.0">
<value>myVal</value>
<method>myMethod</method>
</version>
</name>
<name search="NewValue TTT: write">
<version id="2.0.0">
<value>myVal_2</value>
<method>myMethod_2</method>
</version>
</name>
edited Mar 27 at 11:12
answered Mar 27 at 10:54
DirtyBitDirtyBit
1
1
Thats works but, any way to add this new name elements to the xml file instead of edit the old ones ? (keep the old and add the new)
– falukky
Mar 27 at 12:58
@falukky ofcourse create a new dom element or an empty xml file using beautiful soup and append these to it. This will go outside the current asked question. I suggest you ask a new question with your attempts shown. PS. If this answer helped you may accept it. Cheers! :)
– DirtyBit
Mar 27 at 13:06
add a comment |
Thats works but, any way to add this new name elements to the xml file instead of edit the old ones ? (keep the old and add the new)
– falukky
Mar 27 at 12:58
@falukky ofcourse create a new dom element or an empty xml file using beautiful soup and append these to it. This will go outside the current asked question. I suggest you ask a new question with your attempts shown. PS. If this answer helped you may accept it. Cheers! :)
– DirtyBit
Mar 27 at 13:06
Thats works but, any way to add this new name elements to the xml file instead of edit the old ones ? (keep the old and add the new)
– falukky
Mar 27 at 12:58
Thats works but, any way to add this new name elements to the xml file instead of edit the old ones ? (keep the old and add the new)
– falukky
Mar 27 at 12:58
@falukky ofcourse create a new dom element or an empty xml file using beautiful soup and append these to it. This will go outside the current asked question. I suggest you ask a new question with your attempts shown. PS. If this answer helped you may accept it. Cheers! :)
– DirtyBit
Mar 27 at 13:06
@falukky ofcourse create a new dom element or an empty xml file using beautiful soup and append these to it. This will go outside the current asked question. I suggest you ask a new question with your attempts shown. PS. If this answer helped you may accept it. Cheers! :)
– DirtyBit
Mar 27 at 13:06
add a comment |
from xml.dom.minidom import parse #minidom does the trick
dom = parse('my_file.xml') #read in your file
res = dom.getElementsByTagName('name') #fetch the desired elements in the tree
for element in res: #loop through all
if element.getAttribute('search') == 'read TTT: write': #filter for the attribute and value
element.setAttribute('search', 'New Value TTT: write') #in case of match, replace
with open('my_file_updated.xml','w') as f: #store the file
f.write(dom.toxml())
Thanks, any way to add this new name elements to the xml file instead of edit the old ones ?
– falukky
Mar 27 at 12:00
add a comment |
from xml.dom.minidom import parse #minidom does the trick
dom = parse('my_file.xml') #read in your file
res = dom.getElementsByTagName('name') #fetch the desired elements in the tree
for element in res: #loop through all
if element.getAttribute('search') == 'read TTT: write': #filter for the attribute and value
element.setAttribute('search', 'New Value TTT: write') #in case of match, replace
with open('my_file_updated.xml','w') as f: #store the file
f.write(dom.toxml())
Thanks, any way to add this new name elements to the xml file instead of edit the old ones ?
– falukky
Mar 27 at 12:00
add a comment |
from xml.dom.minidom import parse #minidom does the trick
dom = parse('my_file.xml') #read in your file
res = dom.getElementsByTagName('name') #fetch the desired elements in the tree
for element in res: #loop through all
if element.getAttribute('search') == 'read TTT: write': #filter for the attribute and value
element.setAttribute('search', 'New Value TTT: write') #in case of match, replace
with open('my_file_updated.xml','w') as f: #store the file
f.write(dom.toxml())
from xml.dom.minidom import parse #minidom does the trick
dom = parse('my_file.xml') #read in your file
res = dom.getElementsByTagName('name') #fetch the desired elements in the tree
for element in res: #loop through all
if element.getAttribute('search') == 'read TTT: write': #filter for the attribute and value
element.setAttribute('search', 'New Value TTT: write') #in case of match, replace
with open('my_file_updated.xml','w') as f: #store the file
f.write(dom.toxml())
answered Mar 27 at 11:34
The WecknessThe Weckness
1114 bronze badges
1114 bronze badges
Thanks, any way to add this new name elements to the xml file instead of edit the old ones ?
– falukky
Mar 27 at 12:00
add a comment |
Thanks, any way to add this new name elements to the xml file instead of edit the old ones ?
– falukky
Mar 27 at 12:00
Thanks, any way to add this new name elements to the xml file instead of edit the old ones ?
– falukky
Mar 27 at 12:00
Thanks, any way to add this new name elements to the xml file instead of edit the old ones ?
– falukky
Mar 27 at 12:00
add a comment |
Try This:
xml = """<?xml version="1.0" encoding="UTF-8"?>
<body>
<name search = "read TTT: write">
<version id = "1.0.0">
<value>myVal</value>
<method>myMethod</method>
</version>
</name>
<name search = "read TTT: write">
<version id = "1.0.0">
<value>myVal</value>
<method>myMethod</method>
</version>
</name>
</body>
"""
import xml.etree.ElementTree as ET
tree = ET.fromstring(xml)
sh = tree.findall('name')
for name in sh:
val = name.get("search")
if str(val) == "read TTT: write":
name.set('search', 'NewValue TTT: write')
print (ET.tostring(tree))
Output:
<body>
<name search = "NewValue TTT: write">
<version id = "1.0.0">
<value>myVal</value>
<method>myMethod</method>
</version>
</name>
<name search = "NewValue TTT: write">
<version id = "1.0.0">
<value>myVal</value>
<method>myMethod</method>
</version>
</name>
</body>
This print only the first name element and my XML have mane name elements
– falukky
Mar 27 at 11:06
@falukky :Try the Updated code
– Suraj M
Mar 27 at 11:16
add a comment |
Try This:
xml = """<?xml version="1.0" encoding="UTF-8"?>
<body>
<name search = "read TTT: write">
<version id = "1.0.0">
<value>myVal</value>
<method>myMethod</method>
</version>
</name>
<name search = "read TTT: write">
<version id = "1.0.0">
<value>myVal</value>
<method>myMethod</method>
</version>
</name>
</body>
"""
import xml.etree.ElementTree as ET
tree = ET.fromstring(xml)
sh = tree.findall('name')
for name in sh:
val = name.get("search")
if str(val) == "read TTT: write":
name.set('search', 'NewValue TTT: write')
print (ET.tostring(tree))
Output:
<body>
<name search = "NewValue TTT: write">
<version id = "1.0.0">
<value>myVal</value>
<method>myMethod</method>
</version>
</name>
<name search = "NewValue TTT: write">
<version id = "1.0.0">
<value>myVal</value>
<method>myMethod</method>
</version>
</name>
</body>
This print only the first name element and my XML have mane name elements
– falukky
Mar 27 at 11:06
@falukky :Try the Updated code
– Suraj M
Mar 27 at 11:16
add a comment |
Try This:
xml = """<?xml version="1.0" encoding="UTF-8"?>
<body>
<name search = "read TTT: write">
<version id = "1.0.0">
<value>myVal</value>
<method>myMethod</method>
</version>
</name>
<name search = "read TTT: write">
<version id = "1.0.0">
<value>myVal</value>
<method>myMethod</method>
</version>
</name>
</body>
"""
import xml.etree.ElementTree as ET
tree = ET.fromstring(xml)
sh = tree.findall('name')
for name in sh:
val = name.get("search")
if str(val) == "read TTT: write":
name.set('search', 'NewValue TTT: write')
print (ET.tostring(tree))
Output:
<body>
<name search = "NewValue TTT: write">
<version id = "1.0.0">
<value>myVal</value>
<method>myMethod</method>
</version>
</name>
<name search = "NewValue TTT: write">
<version id = "1.0.0">
<value>myVal</value>
<method>myMethod</method>
</version>
</name>
</body>
Try This:
xml = """<?xml version="1.0" encoding="UTF-8"?>
<body>
<name search = "read TTT: write">
<version id = "1.0.0">
<value>myVal</value>
<method>myMethod</method>
</version>
</name>
<name search = "read TTT: write">
<version id = "1.0.0">
<value>myVal</value>
<method>myMethod</method>
</version>
</name>
</body>
"""
import xml.etree.ElementTree as ET
tree = ET.fromstring(xml)
sh = tree.findall('name')
for name in sh:
val = name.get("search")
if str(val) == "read TTT: write":
name.set('search', 'NewValue TTT: write')
print (ET.tostring(tree))
Output:
<body>
<name search = "NewValue TTT: write">
<version id = "1.0.0">
<value>myVal</value>
<method>myMethod</method>
</version>
</name>
<name search = "NewValue TTT: write">
<version id = "1.0.0">
<value>myVal</value>
<method>myMethod</method>
</version>
</name>
</body>
edited Mar 27 at 11:16
answered Mar 27 at 10:57
Suraj MSuraj M
37210 bronze badges
37210 bronze badges
This print only the first name element and my XML have mane name elements
– falukky
Mar 27 at 11:06
@falukky :Try the Updated code
– Suraj M
Mar 27 at 11:16
add a comment |
This print only the first name element and my XML have mane name elements
– falukky
Mar 27 at 11:06
@falukky :Try the Updated code
– Suraj M
Mar 27 at 11:16
This print only the first name element and my XML have mane name elements
– falukky
Mar 27 at 11:06
This print only the first name element and my XML have mane name elements
– falukky
Mar 27 at 11:06
@falukky :Try the Updated code
– Suraj M
Mar 27 at 11:16
@falukky :Try the Updated code
– Suraj M
Mar 27 at 11:16
add a comment |
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55374724%2fpython-read-all-elements-in-xaml-file-and-replace-some-values%23new-answer', 'question_page');
);
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Possible duplicate of Find replace Element using Python
– Nenri
Mar 27 at 10:18
The string you want to replace with is always the same?
– Alderven
Mar 27 at 10:19
user @Alderven : no, this line: read TTT: write start here with read, so all the elements that name start with read i want to replace
– falukky
Mar 27 at 10:21
Could you please add expected XML sample?
– Alderven
Mar 27 at 10:23
please see my update
– falukky
Mar 27 at 10:27